此版本仍在开发中,尚未被视为稳定版本。最新的快照版本请使用 Spring AI 1.0.0-SNAPSHOT!spring-doc.cadn.net.cn

Neo4j

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

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

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

先决条件

自动配置

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

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

或发送到您的 Gradlebuild.gradlebuild 文件。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-neo4j-store-spring-boot-starter'
}
请参阅 Dependency Management 部分,将 Spring AI BOM 添加到您的构建文件中。

请查看 vector store 的配置参数列表,了解默认值和配置选项。spring-doc.cadn.net.cn

请参阅 Repositories 部分,将 Maven Central 和/或 Snapshot Repositories 添加到您的构建文件中。

矢量存储实现可以为您初始化必要的架构,但您必须通过指定initializeSchemaboolean 或设置…​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
        dimensions: 1536
        distance-type: cosine
        batching-strategy: TOKEN_COUNT # Optional: Controls how documents are batched for embedding

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

用于使用 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

是否初始化所需的 schemaspring-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.dimensionsspring-doc.cadn.net.cn

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

1536spring-doc.cadn.net.cn

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

要使用的 distance 函数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.ai.vectorstore.neo4j.batching-strategyspring-doc.cadn.net.cn

计算嵌入时对文档进行批处理的策略。选项包括TOKEN_COUNTFIXED_SIZEspring-doc.cadn.net.cn

TOKEN_COUNTspring-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.gradlebuild 文件。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-neo4j-store'
}
请参阅 Dependency Management 部分,将 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>"));
}

然后创建Neo4jVectorStore使用 Builder 模式的 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
        .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 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"

访问 Native Client

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