获取最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

Neo4j

本节将引导您完成配置Neo4jVectorStore以存储文档嵌入并执行相似性搜索的过程。spring-doc.cadn.net.cn

Neo4j 是一个开源的非关系型图数据库。 它是一个完全的事务型数据库(ACID),以图结构存储数据,由节点和关系组成。这种数据库借鉴了现实世界中的结构,允许在复杂数据上进行高查询性能,同时保持直观和简单,便于开发者使用。spring-doc.cadn.net.cn

Neo4j的向量化检索(Neo4j’s Vector Search)允许用户从大规模数据集中查询向量嵌入体。 一个嵌入体是数据对象的数值表示,可以是文本、图像、音频或文档。 这些嵌入体可以存储在Node属性中,并使用0函数进行查询。 这些索引由Lucene驱动,基于分层可 navigable 小世界图 (HNSW) 进行k近似最近邻居 (k-ANN) 查询。spring-doc.cadn.net.cn

前提条件

自动配置

There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。spring-doc.cadn.net.cn

Spring AI 提供 Spring Boot 自配置功能支持Neo4j向量数据库。 要启用它,请在您的项目Maven pom.xml 文件中添加以下依赖项:spring-doc.cadn.net.cn

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

或者添加到您的Gradle 构建脚本文件中。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-neo4j'
}
参考以下依赖管理部分,添加Spring AI BOM到你的构建文件中。

请查看向量存储中配置属性列表,以了解默认值和配置选项。spring-doc.cadn.net.cn

引用 Artifact 仓库 部分,以在构建文件中添加 Maven Central 和/或 Snapshot 仓库。

The vector store implementation can initialize the requisite schema for you, but you must opt-in by specifying the initializeSchema boolean in the appropriate constructor or by setting …​initialize-schema=true in the application.properties file.spring-doc.cadn.net.cn

这是一个破坏性变更!在早期版本的 Spring AI 中,此模式初始化是默认进行的。

此外,您还需要配置一个EmbeddingModel的豆。有关详细信息,请参阅EmbeddingModel部分。spring-doc.cadn.net.cn

现在您可以在应用程序中自动将Neo4jVectorStore作为向量存储进行注入。spring-doc.cadn.net.cn

@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-doc.cadn.net.cn

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
        embedding-dimension: 1536
        distance-type: cosine

Spring Boot的以spring.neo4j.*开头的属性用于配置Neo4j客户端:spring-doc.cadn.net.cn

属性 描述 默认值

spring.neo4j.urispring-doc.cadn.net.cn

连接到Neo4j实例的URIspring-doc.cadn.net.cn

neo4j://localhost:7687spring-doc.cadn.net.cn

spring.neo4j.authentication.usernamespring-doc.cadn.net.cn

Neo4j认证用户用户名spring-doc.cadn.net.cn

neo4jspring-doc.cadn.net.cn

spring.neo4j.authentication.passwordspring-doc.cadn.net.cn

用于身份验证的密码,与Neo4jspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.neo4j.* 开头的属性用于配置 Neo4jVectorStorespring-doc.cadn.net.cn

属性 描述 默认值

spring.ai.vectorstore.neo4j.initialize-schemaspring-doc.cadn.net.cn

是否初始化所需的模式spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.vectorstore.neo4j.database-namespring-doc.cadn.net.cn

需要使用的Neo4j数据库的名称spring-doc.cadn.net.cn

neo4jspring-doc.cadn.net.cn

spring.ai.vectorstore.neo4j.index-namespring-doc.cadn.net.cn

存储向量的索引名称spring-doc.cadn.net.cn

spring-ai-document-indexspring-doc.cadn.net.cn

spring.ai.vectorstore.neo4j.embedding-dimensionspring-doc.cadn.net.cn

向量中的维度数量spring-doc.cadn.net.cn

1536spring-doc.cadn.net.cn

spring.ai.vectorstore.neo4j.distance-typespring-doc.cadn.net.cn

距离函数的使用spring-doc.cadn.net.cn

cosinespring-doc.cadn.net.cn

spring.ai.vectorstore.neo4j.labelspring-doc.cadn.net.cn

用于文档节点的标签spring-doc.cadn.net.cn

Documentspring-doc.cadn.net.cn

spring.ai.vectorstore.neo4j.embedding-propertyspring-doc.cadn.net.cn

用于存储嵌入的属性名称spring-doc.cadn.net.cn

embeddingspring-doc.cadn.net.cn

以下距离函数可用:spring-doc.cadn.net.cn

  • cosine - 默认值,适用于大多数用例。衡量向量之间的余弦相似度。spring-doc.cadn.net.cn

  • euclidean - 向量之间的欧几里得距离。数值越低,表示相似度越高。spring-doc.cadn.net.cn

手动配置

无需使用Spring Boot的自动配置,您可以通过手动配置Neo4j向量存储来实现。为此,您需要将 spring-ai-neo4j-store 添加到您的项目中:spring-doc.cadn.net.cn

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

或者添加到您的Gradle 构建脚本文件中。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-neo4j-store'
}
参考以下依赖管理部分,添加Spring AI BOM到你的构建文件中。

创建一个Neo4j 0号bean。 阅读Neo4j文档以获取更多关于自定义驱动器配置的深入信息。spring-doc.cadn.net.cn

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

然后使用构建器模式创建 Neo4jVectorStore Bean:spring-doc.cadn.net.cn

@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
        .embeddingDimension(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")));
}

元数据过滤

You can leverage the generic, portable 元数据过滤器 with Neo4j store as well.spring-doc.cadn.net.cn

例如,你可以使用文本表达式语言:spring-doc.cadn.net.cn

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:spring-doc.cadn.net.cn

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());
Those (可移动的)Filter表达式会自动转换为 proprietary Neo4j 的 WHERE 格式Filter表达式。

例如,这个可移植的过滤表达式:spring-doc.cadn.net.cn

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

将转换为特定的 {Neo4j} 过滤器格式:spring-doc.cadn.net.cn

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

访问原生客户端

Neo4j向量存储实现通过提供访问底层的Neo4j客户端(Driver)的方法,使用(getNativeClient())实现。spring-doc.cadn.net.cn

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接口暴露出来。spring-doc.cadn.net.cn