Neo4j

このセクションでは、ドキュメントの埋め込みを保存し、類似性検索を実行するための Neo4jVectorStore のセットアップについて説明します。

Neo4j (英語) は、オープンソースの NoSQL グラフデータベースです。これは、関連によって接続されたノードで構成されるグラフとして構造化されたデータを保存する、完全なトランザクションデータベース (ACID) です。現実世界の構造からインスピレーションを得たこのツールは、開発者にとって直感的でシンプルなままでありながら、複雑なデータに対する高いクエリパフォーマンスを可能にします。

Neo4j のベクトル検索 (英語) を使用すると、ユーザーは大規模なデータセットからベクトル埋め込みをクエリできます。埋め込みとは、テキスト、イメージ、音声、ドキュメントなどのデータオブジェクトの数値表現です。埋め込みはノードプロパティに保存でき、db.index.vector.queryNodes() 関数でクエリできます。これらのインデックスは、階層型ナビゲート可能なスモールワールドグラフ (HNSW) を使用して Lucene によって強化され、ベクトルフィールドに対して k 近似最近傍 (k-ANN) クエリを実行します。

前提条件

自動構成

Spring AI は、Neo4j ベクトルストアの Spring Boot 自動構成を提供します。これを有効にするには、プロジェクトの Maven pom.xml ファイルに次の依存関係を追加します。

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-neo4j-store-spring-boot-starter</artifactId>
</dependency>

または、Gradle build.gradle ビルドファイルに保存します。

dependencies {
    implementation 'org.springframework.ai:spring-ai-neo4j-store-spring-boot-starter'
}
Spring AI BOM をビルドファイルに追加するには、"依存関係管理" セクションを参照してください。

デフォルト値と構成オプションについては、ベクトルストアの構成パラメーターのリストを参照してください。

リポジトリセクションを参照して、ビルドファイルに Maven Central リポジトリやスナップショットリポジトリを追加します。

ベクトルストアの実装では必要なスキーマを初期化できますが、適切なコンストラクターで initializeSchema ブール値を指定するか、application.properties ファイルで …​initialize-schema=true を設定することによってオプトインする必要があります。

これは重大な変更です。Spring AI の以前のバージョンでは、このスキーマの初期化はデフォルトで行われていました。

さらに、設定済みの EmbeddingModel Bean が必要です。詳細については、"EmbeddingModel" セクションを参照してください。

これで、Neo4jVectorStore をアプリケーション内のベクトルストアとして自動接続できるようになりました。

@Autowired VectorStore vectorStore;

// ...

List<Document> documents = List.of(
    new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")),
    new Document("The World is Big and Salvation Lurks Around the Corner"),
    new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2")));

// Add the documents to Neo4j
vectorStore.add(documents);

// Retrieve documents similar to a query
List<Document> results = vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());

プロパティの構成

Neo4j に接続して Neo4jVectorStore を使用するには、インスタンスのアクセス詳細を提供する必要があります。簡単な構成は、Spring Boot の application.yml を介して提供できます。

spring:
  neo4j:
    uri: <neo4j instance URI>
    authentication:
      username: <neo4j username>
      password: <neo4j password>
  ai:
    vectorstore:
      neo4j:
        initialize-schema: true
        database-name: neo4j
        index-name: custom-index
        dimensions: 1536
        distance-type: cosine
        batching-strategy: TOKEN_COUNT # Optional: Controls how documents are batched for embedding

spring.neo4j.* で始まる Spring Boot プロパティは、Neo4j クライアントを構成するために使用されます。

プロパティ 説明 デフォルト値

spring.neo4j.uri

Neo4j インスタンスに接続するための URI

neo4j://localhost:7687

spring.neo4j.authentication.username

Neo4j での認証用のユーザー名

neo4j

spring.neo4j.authentication.password

Neo4j での認証用パスワード

-

spring.ai.vectorstore.neo4j.* で始まるプロパティは、Neo4jVectorStore を構成するために使用されます。

プロパティ 説明 デフォルト値

spring.ai.vectorstore.neo4j.initialize-schema

必要なスキーマを初期化するかどうか

false

spring.ai.vectorstore.neo4j.database-name

使用する Neo4j データベースの名前

neo4j

spring.ai.vectorstore.neo4j.index-name

ベクトルを格納するインデックスの名前

spring-ai-document-index

spring.ai.vectorstore.neo4j.dimensions

ベクトルの次元数

1536

spring.ai.vectorstore.neo4j.distance-type

使用する距離関数

cosine

spring.ai.vectorstore.neo4j.label

ドキュメントノードに使用されるラベル

Document

spring.ai.vectorstore.neo4j.embedding-property

埋め込みを保存するために使用されるプロパティ名

embedding

spring.ai.vectorstore.neo4j.batching-strategy

埋め込みを計算するときにドキュメントをバッチ処理する戦略。オプションは TOKEN_COUNT または FIXED_SIZE です

TOKEN_COUNT

次の距離関数が利用可能です:

  • cosine - デフォルト。ほとんどのユースケースに適しています。ベクトル間のコサイン類似度を測定します。

  • euclidean - ベクトル間のユークリッド距離。値が低いほど類似性が高くなります。

手動構成

Spring Boot 自動構成を使用する代わりに、Neo4j ベクトルストアを手動で構成できます。そのためには、プロジェクトに spring-ai-neo4j-store を追加する必要があります。

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-neo4j-store</artifactId>
</dependency>

または、Gradle build.gradle ビルドファイルに保存します。

dependencies {
    implementation 'org.springframework.ai:spring-ai-neo4j-store'
}
Spring AI BOM をビルドファイルに追加するには、"依存関係管理" セクションを参照してください。

Neo4j Driver Bean を作成します。カスタムドライバーの構成に関する詳細については、Neo4j ドキュメント (英語) を参照してください。

@Bean
public Driver driver() {
    return GraphDatabase.driver("neo4j://<host>:<bolt-port>",
            AuthTokens.basic("<username>", "<password>"));
}

次に、ビルダーパターンを使用して Neo4jVectorStore Bean を作成します。

@Bean
public VectorStore vectorStore(Driver driver, EmbeddingModel embeddingModel) {
    return Neo4jVectorStore.builder(driver, embeddingModel)
        .databaseName("neo4j")                // Optional: defaults to "neo4j"
        .distanceType(Neo4jDistanceType.COSINE) // Optional: defaults to COSINE
        .dimensions(1536)                      // Optional: defaults to 1536
        .label("Document")                     // Optional: defaults to "Document"
        .embeddingProperty("embedding")        // Optional: defaults to "embedding"
        .indexName("custom-index")             // Optional: defaults to "spring-ai-document-index"
        .initializeSchema(true)                // Optional: defaults to false
        .batchingStrategy(new TokenCountBatchingStrategy()) // Optional: defaults to TokenCountBatchingStrategy
        .build();
}

// This can be any EmbeddingModel implementation
@Bean
public EmbeddingModel embeddingModel() {
    return new OpenAiEmbeddingModel(new OpenAiApi(System.getenv("OPENAI_API_KEY")));
}

メタデータフィルタリング

Neo4j ストアでは、汎用のポータブルなメタデータフィルターを利用することもできます。

例: 次のいずれかのテキスト式言語を使用できます。

vectorStore.similaritySearch(
    SearchRequest.builder()
        .query("The World")
        .topK(TOP_K)
        .similarityThreshold(SIMILARITY_THRESHOLD)
        .filterExpression("author in ['john', 'jill'] && 'article_type' == 'blog'").build());

または、Filter.Expression DSL を使用してプログラム的に次のようにします。

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(SearchRequest.builder()
    .query("The World")
    .topK(TOP_K)
    .similarityThreshold(SIMILARITY_THRESHOLD)
    .filterExpression(b.and(
        b.in("author", "john", "jill"),
        b.eq("article_type", "blog")).build()).build());
これらの (ポータブル) フィルター式は、独自の Neo4j WHERE  フィルター式 (英語) に自動的に変換されます。

例: この移植可能なフィルター式:

author in ['john', 'jill'] && 'article_type' == 'blog'

独自の Neo4j フィルター形式に変換されます。

node.`metadata.author` IN ["john","jill"] AND node.`metadata.'article_type'` = "blog"

ネイティブクライアントへのアクセス

Neo4j ベクトルストア実装は、getNativeClient() メソッドを通じて、基盤となるネイティブ Neo4j クライアント (Driver) へのアクセスを提供します。

Neo4jVectorStore vectorStore = context.getBean(Neo4jVectorStore.class);
Optional<Driver> nativeClient = vectorStore.getNativeClient();

if (nativeClient.isPresent()) {
    Driver driver = nativeClient.get();
    // Use the native client for Neo4j-specific operations
}

ネイティブクライアントを使用すると、VectorStore インターフェースでは公開されない可能性のある Neo4j 固有の機能と操作にアクセスできます。