Neo4j
本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。 |
本节将指导你设置 Neo4jVectorStore 用于存储文档嵌入并执行相似性搜索。
Neo4j 是一个开源的 NoSQL 图数据库。作为完全支持事务的数据库(ACID),它以图结构存储数据,包含由关系连接的节点。其设计灵感源于现实世界结构,在保持开发直观性和简洁性的同时,能高效处理复杂数据查询。
Neo4j 的向量搜索 支持用户从大数据集中查询向量嵌入。嵌入是数据对象(如文本、图像、音频或文档)的数值表示,可存储在节点属性中,并通过 db.index.vector.queryNodes()
函数查询。这些索引由 Lucene 驱动,使用分层可导航小世界图(HNSW)对向量字段执行 k 近似最近邻(k-ANN)查询。
先决条件
-
运行中的 Neo4j(5.15+)实例。有以下选项:
-
如果需要,还需要 EmbeddingModel 的 API Key,以便生成由
Neo4jVectorStore
存储的嵌入信息。
自动配置
Spring AI 的自动配置及 Starter 模块的构件名称发生重大变更。详情请查阅 升级说明。 |
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 仓库” 部分将 Maven Central 和/或 Snapshot Repositories 添加至构建文件。 |
向量存储实现可以为你初始化所需模式,但你必须通过指定适当构造函数中的 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 客户端:
属性 | 说明 | 默认值 |
---|---|---|
|
连接 Neo4j 实例的 URI。 |
|
|
用于 Neo4j 认证的用户名。 |
|
|
用于 Neo4j 认证的密码。 |
- |
以 spring.ai.vectorstore.neo4j.*
开头的属性用于配置 Neo4jVectorStore
:
属性 | 说明 | 默认值 |
---|---|---|
|
是否初始化所需 Schema。 |
|
|
使用的 Neo4j 数据库名称。 |
|
|
存储向量的索引名称。 |
|
|
向量的维度数量。 |
|
|
使用的距离函数。 |
|
|
文档节点使用的标签。 |
|
|
存储嵌入的属性名称。 |
|
可用的距离函数如下:
-
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>"));
}
随后通过 Builder 模式创建 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 向量存储实现通过 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
}
原生客户端可访问 Neo4j 特有功能及操作,这些可能未通过 VectorStore
接口暴露。