Neo4j
本節將引導您設定 Neo4jVectorStore 來儲存文件嵌入並執行相似性搜尋。
Neo4j 是一個開源的 NoSQL 圖資料庫。它是一個完全事務性的資料庫 (ACID),將資料結構儲存為由節點組成,並透過關係連線的圖。受現實世界結構的啟發,它允許在複雜資料上實現高查詢效能,同時對於開發人員來說保持直觀和簡單。
Neo4j 的向量搜尋 允許使用者從大型資料集中查詢向量嵌入。嵌入是資料物件(如文字、影像、音訊或文件)的數值表示。嵌入可以儲存在 節點 屬性上,並可以使用 db.index.vector.queryNodes() 函式進行查詢。這些索引由 Lucene 提供支援,使用分層可導航小世界圖 (HNSW) 對向量欄位執行 k 近似最近鄰 (k-ANN) 查詢。
先決條件
-
正在執行的 Neo4j (5.15+) 例項。以下選項可用:
-
如果需要,還需要 EmbeddingModel 的 API 金鑰,用於生成由
Neo4jVectorStore儲存的嵌入。
自動配置
|
Spring AI 自動配置、啟動模組的工件名稱發生了重大變化。請參閱 升級說明 以獲取更多資訊。 |
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 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
| 財產 | 描述 | 預設值 |
|---|---|---|
|
是否初始化所需的模式 |
|
|
要使用的 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>"));
}
然後使用構建器模式建立 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
}
原生客戶端允許您訪問 VectorStore 介面可能未公開的 Neo4j 特定功能和操作。