Neo4j
本节将引导你如何设置Neo4jVectorStore用于存储文档嵌入并进行相似性搜索。
Neo4j 是一个开源的 NoSQL 图数据库。 它是一个完全事务型数据库(ACID),存储由节点组成的图结构化数据,这些节点通过关系连接。 它受现实世界的结构启发,能够在复杂数据上实现高查询性能,同时对开发者保持直观和简洁。
Neo4j 的向量搜索允许用户查询大型数据集中的向量嵌入。
嵌入是数据对象的数值表示,例如文本、图像、音频或文档。
嵌入可以存储在节点属性上,并可用db.index.vector.queryNodes()功能。
这些索引由Lucene提供,使用分层可导航小世界图(HNSW)对向量场进行k个近似最近邻(k-ANN)查询。
前提条件
-
一个运行中的Neo4j(5.15+)实例。以下选项可供选择:
-
Docker 镜像
-
Neo4j Server instance
-
-
如有需要,需为 EmbeddingModel 提供 API 密钥,以生成存储于
Neo4jVectorStore.
自动配置
|
春季AI自动配置、起始模块的工件名称发生了重大变化。 更多信息请参阅升级说明。 |
Spring AI 为 Neo4j 向量存储提供了 Spring Boot 自动配置。
要启用它,请在项目的 Maven 中添加以下依赖pom.xml文件:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-neo4j</artifactId>
</dependency>
或者去你的Gradlebuild.gradle构建文件。
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-neo4j'
}
| 请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。 |
请查看矢量存储的配置属性列表,了解默认值和配置选项。
| 请参阅“遗物仓库”部分,将Maven Central和/或快照仓库添加到你的构建文件中。 |
向量存储实现可以帮你初始化所需的模式,但你必须通过指定初始化模式在适当的构造函数中进行布尔值,或通过设置…initialize-schema=true在application.properties文件。
| 这是一个颠覆性的变革!在早期版本的 Spring AI 中,这种模式初始化是默认的。 |
此外,你还需要一个配置嵌入模型豆。 更多信息请参阅嵌入模型部分。
现在你可以自动接线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 Boot 属性Spring.neo4j.*用于配置 Neo4j 客户端:
| 属性 | 描述 | 默认值 |
|---|---|---|
|
连接 Neo4j 实例的 URI |
|
|
Neo4j 认证用户名 |
|
|
用于 Neo4j 认证的密码 |
- |
性质以spring.ai.vectorstore.neo4j.*用于配置Neo4jVectorStore:
| 属性 | 描述 | 默认值 |
|---|---|---|
|
是否初始化所需的模式 |
|
|
Neo4j数据库的名称 |
|
|
用于存储向量的索引名称 |
|
|
向量中的维数 |
|
|
使用距离函数 |
|
|
用于文档节点的标签 |
|
|
该物业名称用于存储嵌入 |
|
可用的距离函数如下:
-
余弦- 默认,适用于大多数用例。测量向量之间的余弦相似度。 -
欧 氏- 向量之间的欧几里得距离。数值越低表示相似度越高。
手动配置
你可以手动配置 Neo4j 矢量存储,而不是用 Spring Boot 的自动配置。为此你需要添加Spring-ai-neo4j-store致你的项目:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-neo4j-store</artifactId>
</dependency>
或者去你的Gradlebuild.gradle构建文件。
dependencies {
implementation 'org.springframework.ai:spring-ai-neo4j-store'
}
| 请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。 |
创建一个Neo4jDrivers豆。
阅读 Neo4j 文档,获取更深入的自定义驱动配置信息。
@Bean
public Driver driver() {
return GraphDatabase.driver("neo4j://<host>:<bolt-port>",
AuthTokens.basic("<username>", "<password>"));
}
然后创建Neo4jVectorStore使用构建图纸的豆子:
@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());
或者程序化地使用滤波。表达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哪里 过滤表达。 |
例如,这个可移植的Filter表达式:
author in ['john', 'jill'] && 'article_type' == 'blog'
转换为专有的Neo4jFilter格式:
node.`metadata.author` IN ["john","jill"] AND node.`metadata.'article_type'` = "blog"
访问本地客户端
Neo4j 向量存储实现提供了对底层原生 Neo4j 客户端的访问(Drivers)通过getNativeClient()方法:
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接口。