跳到主要内容

Neo4j

Deepseek 3.2 中英对照 Neo4j

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

Neo4j 是一个开源 NoSQL 图形数据库。它是一个完全支持事务的数据库(ACID),以图的形式存储数据,这些图由通过关系连接的节点组成。其设计灵感源于现实世界的结构,能够在处理复杂数据时保持高性能的查询能力,同时为开发者提供直观且简单的使用体验。

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

先决条件

Auto-configuration

备注

Spring AI 的自动配置和 starter 模块的 artifact 名称发生了重大变更。更多信息请参考升级说明

Spring AI 为 Neo4j 向量存储提供了 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添加到您的构建文件中。
:::

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

提示

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

向量存储实现可以为您初始化必需的模式,但您必须通过在适当的构造函数中指定 initializeSchema 布尔值,或在 application.properties 文件中设置 …​initialize-schema=true 来选择启用此功能。

备注

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

此外,你还需要一个配置好的 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
embedding-dimension: 1536
distance-type: cosine

spring.neo4j.* 开头的 Spring Boot 属性用于配置 Neo4j 客户端:

属性说明默认值
spring.neo4j.uri用于连接 Neo4j 实例的 URIneo4j://localhost:7687
spring.neo4j.authentication.username用于向 Neo4j 进行身份验证的用户名neo4j
spring.neo4j.authentication.password用于向 Neo4j 进行身份验证的密码-

spring.ai.vectorstore.neo4j.* 开头的属性用于配置 Neo4jVectorStore

属性描述默认值
spring.ai.vectorstore.neo4j.initialize-schema是否初始化所需的 schemafalse
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 的属性名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
.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 存储。

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

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
}

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