Spring AI / Vector Databases / Neo4j

Spring AI

参考文档

向量数据库

Neo4j

Neo4j

本节将引导您设置 Neo4jVectorStore,用于存储文档嵌入并执行相似性搜索。

Neo4j 是一个开源的 NoSQL 图数据库。它是一个完全支持事务的数据库(ACID),将数据存储为由节点和连接节点的关系组成的图结构。受现实世界结构的启发,它能够在保持对开发者直观和简单的同时,对复杂数据提供高查询性能。

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

前置条件

  • 一个正在运行的 Neo4j(5.15+)实例。可以使用以下选项:
    • Docker 镜像
    • Neo4j Desktop
    • Neo4j Aura
    • Neo4j Server 实例
  • 如果需要,需要为 EmbeddingModel 提供 API 密钥,以生成由 Neo4jVectorStore 存储的嵌入。

自动配置

关于 Spring AI 自动配置和启动器模块的 artifact 名称有重大变更。请参阅升级说明以获取更多信息。

Spring AI 为 Neo4j 向量存储提供了 Spring Boot 自动配置。要启用它,请将以下依赖项添加到您项目的 Maven pom.xml 文件中:

xml 复制代码
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-vector-store-neo4j</artifactId>
</dependency>

或者添加到您的 Gradle build.gradle 构建文件中。

gradle 复制代码
dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-neo4j'
}

请参阅依赖管理部分,将 Spring AI BOM 添加到您的构建文件中。

请查看向量存储的配置属性列表,以了解默认值和配置选项。

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

向量存储实现可以为您初始化所需的模式,但您必须选择加入,方法是在适当的构造函数中指定 initializeSchema 布尔值,或者在 application.properties 文件中设置 ...​initialize-schema=true

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

此外,您还需要一个已配置的 EmbeddingModel bean。请参阅嵌入模型部分以获取更多信息。

现在,您可以在应用程序中自动装配 Neo4jVectorStore 作为向量存储。

java 复制代码
@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")));

// 将文档添加到 Neo4j
vectorStore.add(documents);

// 检索与查询相似的文档
List<Document> results = vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());

配置属性

要连接到 Neo4j 并使用 Neo4jVectorStore,您需要为您的实例提供访问详细信息。可以通过 Spring Boot 的 application.yml 提供简单配置:

yaml 复制代码
spring:
  neo4j:
    uri: <neo4j 实例 URI>
    authentication:
      username: <neo4j 用户名>
      password: <neo4j 密码>
  ai:
    vectorstore:
      neo4j:
        initialize-schema: true
        database-name: neo4j
        index-name: custom-index
        embedding-dimension: 1536
        distance-type: cosine

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.embedding-dimension 向量的维度数 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 添加到您的项目中:

xml 复制代码
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-neo4j-store</artifactId>
</dependency>

或者添加到您的 Gradle build.gradle 构建文件中。

gradle 复制代码
dependencies {
    implementation 'org.springframework.ai:spring-ai-neo4j-store'
}

请参阅依赖管理部分,将 Spring AI BOM 添加到您的构建文件中。

创建一个 Neo4j Driver bean。请阅读 Neo4j 文档,以获取有关自定义驱动程序配置的更深入信息。

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

然后使用构建器模式创建 Neo4jVectorStore bean:

java 复制代码
@Bean
public VectorStore vectorStore(Driver driver, EmbeddingModel embeddingModel) {
    return Neo4jVectorStore.builder(driver, embeddingModel)
        .databaseName("neo4j")                // 可选:默认为 "neo4j"
        .distanceType(Neo4jDistanceType.COSINE) // 可选:默认为 COSINE
        .embeddingDimension(1536)                      // 可选:默认为 1536
        .label("Document")                     // 可选:默认为 "Document"
        .embeddingProperty("embedding")        // 可选:默认为 "embedding"
        .indexName("custom-index")             // 可选:默认为 "spring-ai-document-index"
        .initializeSchema(true)                // 可选:默认为 false
        .batchingStrategy(new TokenCountBatchingStrategy()) // 可选:默认为 TokenCountBatchingStrategy
        .build();
}

// 这可以是任何 EmbeddingModel 实现
@Bean
public EmbeddingModel embeddingModel() {
    return new OpenAiEmbeddingModel(OpenAiEmbeddingOptions.builder().apiKey(System.getenv("OPENAI_API_KEY")).build());
}

元数据过滤

您也可以将通用的、可移植的元数据过滤器与 Neo4j 存储一起使用。

例如,您可以使用文本表达式语言:

java 复制代码
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 以编程方式:

java 复制代码
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)的访问:

java 复制代码
Neo4jVectorStore vectorStore = context.getBean(Neo4jVectorStore.class);
Optional<Driver> nativeClient = vectorStore.getNativeClient();

if (nativeClient.isPresent()) {
    Driver driver = nativeClient.get();
    // 使用原生客户端执行 Neo4j 特定操作
}

原生客户端使您能够访问可能未通过 VectorStore 接口公开的 Neo4j 特定功能和操作。