Neo4j

本節將引導您設定 Neo4jVectorStore 來儲存文件嵌入並執行相似性搜尋。

Neo4j 是一個開源的 NoSQL 圖資料庫。它是一個完全事務性(ACID)的資料庫,以由節點透過關係連線的圖結構儲存資料。受現實世界結構的啟發,它允許在複雜資料上實現高查詢效能,同時對開發人員保持直觀和簡單。

Neo4j 的向量搜尋 (Neo4j’s Vector Search) 允許使用者從大型資料集中查詢向量嵌入。嵌入是資料物件(如文字、影像、音訊或文件)的數值表示。嵌入可以儲存在節點屬性上,並可以使用 db.index.vector.queryNodes() 函式進行查詢。這些索引由 Lucene 提供支援,使用分層可導航小世界圖 (HNSW) 在向量欄位上執行 k 近似最近鄰 (k-ANN) 查詢。

先決條件

自動配置

Spring AI 自動配置、starter 模組的 artifact 名稱發生了重大變化。請參閱升級注意事項以獲取更多資訊。

Spring AI 為 Neo4j Vector Store 提供了 Spring Boot 自動配置。要啟用它,請將以下依賴項新增到專案的 Maven pom.xml 檔案中:

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

或新增到您的 Gradle build.gradle 構建檔案中。

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-neo4j'
}
請參考依賴管理部分,將 Spring AI BOM 新增到您的構建檔案中。

請查看向量儲存的配置引數列表,瞭解預設值和配置選項。

請參考Repositories部分,將 Maven Central 和/或 Snapshot Repositories 新增到您的構建檔案中。

向量儲存實現可以為您初始化所需的 schema,但您必須透過在相應的建構函式中指定 initializeSchema 布林值或在 application.properties 檔案中設定 …​initialize-schema=true 來選擇啟用。

這是一個破壞性變更!在早期版本的 Spring AI 中,此 schema 初始化預設發生。

此外,您還需要一個配置好的 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

spring.neo4j.* 開頭的 Spring Boot 屬性用於配置 Neo4j 客戶端

屬性 描述 預設值

spring.neo4j.uri

連線 Neo4j 例項的 URI

neo4j://:7687

spring.neo4j.authentication.username

用於 Neo4j 認證的使用者名稱

neo4j

spring.neo4j.authentication.password

用於 Neo4j 認證的密碼

-

spring.ai.vectorstore.neo4j.* 開頭的屬性用於配置 Neo4jVectorStore

屬性 描述 預設值

spring.ai.vectorstore.neo4j.initialize-schema

是否初始化所需的 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

可用的距離函式如下:

  • 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 Vector Store 實現透過 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
}

原生客戶端讓您能夠訪問 Neo4j 特定的功能和操作,這些功能和操作可能未透過 VectorStore 介面暴露。