此版本仍在开发中,尚不被认为是稳定的。对于最新的快照版本,请使用 Spring AI 1.0.1spring-doc.cadn.net.cn

Neo4j

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

Neo4j 是一个开源的 NoSQL 图形数据库。 它是一个完全事务的数据库 (ACID),存储结构为由节点组成的图形的数据,并通过关系连接。 受现实世界结构的启发,它允许对复杂数据实现高查询性能,同时对开发人员保持直观和简单。spring-doc.cadn.net.cn

Neo4j 的向量搜索允许用户从大型数据集中查询向量嵌入。 嵌入是数据对象(例如文本、图像、音频或文档)的数字表示。 嵌入可以存储在 Node 属性上,并且可以使用db.index.vector.queryNodes()功能。 这些索引由 Lucene 提供支持,使用分层可导航小世界图 (HNSW) 对向量字段执行 k 个近似最近邻 (k-ANN) 查询。spring-doc.cadn.net.cn

前提条件

自动配置

Spring AI 自动配置、入门模块的工件名称发生了重大变化。 有关更多信息,请参阅升级说明spring-doc.cadn.net.cn

Spring AI 为 Neo4j Vector Store 提供 Spring Boot 自动配置。 要启用它,请将以下依赖项添加到项目的 Mavenpom.xml文件:spring-doc.cadn.net.cn

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

或 Gradlebuild.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 Repositories 部分,将 Maven Central 和/或 Snapshot Repositories 添加到构建文件中。

矢量存储实现可以为您初始化必要的架构,但您必须通过指定initializeSchema布尔值或通过…​initialize-schema=trueapplication.properties文件。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.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

使用 Neo4j 进行身份验证的密码spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.neo4j.*用于配置Neo4jVectorStore:spring-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

手动配置

您可以手动配置 Neo4j 矢量存储,而不是使用 Spring Boot 自动配置。为此,您需要添加spring-ai-neo4j-store到你的项目:spring-doc.cadn.net.cn

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

或 Gradlebuild.gradle构建文件。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-neo4j-store'
}
请参阅依赖项管理部分,将 Spring AI BOM 添加到构建文件中。

创建 Neo4jDriver豆。 阅读 Neo4j 文档,了解有关自定义驱动程序配置的更深入信息。spring-doc.cadn.net.cn

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

然后创建Neo4jVectorStorebean 使用构建器模式: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")));
}

元数据过滤

您也可以在 Neo4j store 中利用通用的、可移植的元数据过滤器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.ExpressionDSL: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());
这些(可移植的)过滤器表达式会自动转换为专有的 Neo4jWHERE 过滤表达式

例如,这个可移植过滤器表达式: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 Vector Store 实现提供对底层原生 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