OpenSearch
本節將引導您設定 OpenSearchVectorStore 以儲存文件嵌入並執行相似性搜尋。
OpenSearch 是一個開源的搜尋和分析引擎,最初從 Elasticsearch 分支而來,並以 Apache 許可證 2.0 釋出。它透過簡化 AI 生成資產的整合和管理來增強 AI 應用程式開發。OpenSearch 支援向量、詞法和混合搜尋功能,利用先進的向量資料庫功能來促進低延遲查詢和相似性搜尋,詳情請參閱向量資料庫頁面。
OpenSearch k-NN 功能允許使用者查詢大型資料集中的向量嵌入。嵌入是資料物件(如文字、影像、音訊或文件)的數值表示。嵌入可以儲存在索引中,並使用各種相似性函式進行查詢。
先決條件
-
正在執行的 OpenSearch 例項。以下選項可用:
-
如果需要,還需要一個 EmbeddingModel 的 API 金鑰,用於生成由
OpenSearchVectorStore儲存的嵌入。
自動配置
|
Spring AI 自動配置、啟動模組的工件名稱發生了重大變化。請參閱 升級說明 以獲取更多資訊。 |
Spring AI 為 OpenSearch 向量儲存提供了 Spring Boot 自動配置。要啟用它,請將以下依賴項新增到您的專案 Maven pom.xml 檔案中
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-opensearch</artifactId>
</dependency>
或新增到您的 Gradle build.gradle 構建檔案中
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-opensearch'
}
| 對於自託管和 Amazon OpenSearch 服務,請使用相同的依賴項。請參閱依賴管理部分,將 Spring AI BOM 新增到您的構建檔案中。 |
請查看向量儲存的配置引數列表,以瞭解預設值和配置選項。
此外,您還需要一個配置的 `EmbeddingModel` bean。有關更多資訊,請參閱EmbeddingModel部分。
現在您可以在應用程式中自動裝配 OpenSearchVectorStore 作為向量儲存
@Autowired VectorStore vectorStore;
// ...
List<Document> documents = List.of(
new Document("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 OpenSearch
vectorStore.add(documents);
// Retrieve documents similar to a query
List<Document> results = vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());
配置屬性
要連線到 OpenSearch 並使用 OpenSearchVectorStore,您需要提供例項的訪問詳細資訊。可以透過 Spring Boot 的 application.yml 提供一個簡單配置
spring:
ai:
vectorstore:
opensearch:
uris: <opensearch instance URIs>
username: <opensearch username>
password: <opensearch password>
index-name: spring-ai-document-index
initialize-schema: true
similarity-function: cosinesimil
read-timeout: <time to wait for response>
connect-timeout: <time to wait until connection established>
path-prefix: <custom path prefix>
ssl-bundle: <name of SSL bundle>
aws: # Only for Amazon OpenSearch Service
host: <aws opensearch host>
service-name: <aws service name>
access-key: <aws access key>
secret-key: <aws secret key>
region: <aws region>
以 spring.ai.vectorstore.opensearch.* 開頭的屬性用於配置 OpenSearchVectorStore
| 財產 | 描述 | 預設值 |
|---|---|---|
|
OpenSearch 叢集端點的 URI |
- |
|
訪問 OpenSearch 叢集的使用者名稱 |
- |
|
指定使用者名稱的密碼 |
- |
|
儲存向量的索引名稱 |
|
|
是否初始化所需的模式 |
|
|
要使用的相似性函式(cosinesimil、l1、l2、linf、innerproduct) |
|
|
是否使用近似 k-NN 進行更快搜索。如果為 true,則使用基於 HNSW 的近似搜尋。如果為 false,則使用精確的暴力 k-NN。請參閱近似 k-NN 和精確 k-NN |
|
|
向量嵌入的維度數量。用於為近似 k-NN 建立索引對映。如果未設定,則使用嵌入模型的維度。 |
|
|
索引的自定義 JSON 對映。覆蓋預設對映生成。 |
- |
|
等待對端響應的時間。0 - 無限。 |
- |
|
等待建立連線的時間。0 - 無限。 |
- |
|
OpenSearch API 端點的路徑字首。當 OpenSearch 位於非根路徑的反向代理後面時很有用。 |
- |
|
在 SSL 連線情況下要使用的 SSL 捆綁包名稱 |
- |
|
OpenSearch 例項的主機名 |
- |
|
AWS 服務名稱 |
- |
|
AWS 訪問金鑰 |
- |
|
AWS 秘密金鑰 |
- |
|
AWS 區域 |
- |
|
您可以使用
此回退邏輯確保使用者可以明確控制 OpenSearch 整合型別,從而避免在不需要時意外啟用 AWS 特定邏輯。 |
|
|
以下相似性函式可用
-
cosinesimil- 預設值,適用於大多數用例。測量向量之間的餘弦相似度。 -
l1- 向量之間的曼哈頓距離。 -
l2- 向量之間的歐幾里得距離。 -
linf- 向量之間的切比雪夫距離。
手動配置
除了使用 Spring Boot 自動配置,您還可以手動配置 OpenSearch 向量儲存。為此,您需要將 spring-ai-opensearch-store 新增到您的專案中
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-opensearch-store</artifactId>
</dependency>
或新增到您的 Gradle build.gradle 構建檔案中
dependencies {
implementation 'org.springframework.ai:spring-ai-opensearch-store'
}
| 請參閱 依賴項管理 部分,將 Spring AI BOM 新增到您的構建檔案中。 |
建立 OpenSearch 客戶端 bean
@Bean
public OpenSearchClient openSearchClient() {
RestClient restClient = RestClient.builder(
HttpHost.create("https://:9200"))
.build();
return new OpenSearchClient(new RestClientTransport(
restClient, new JacksonJsonpMapper()));
}
然後使用構建器模式建立 OpenSearchVectorStore bean
@Bean
public VectorStore vectorStore(OpenSearchClient openSearchClient, EmbeddingModel embeddingModel) {
return OpenSearchVectorStore.builder(openSearchClient, embeddingModel)
.index("custom-index") // Optional: defaults to "spring-ai-document-index"
.similarityFunction("l2") // Optional: defaults to "cosinesimil"
.useApproximateKnn(true) // Optional: defaults to false (exact k-NN)
.dimensions(1536) // Optional: defaults to 1536 or embedding model's dimensions
.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")));
}
元資料過濾
您也可以將通用的、可移植的元資料過濾器與 OpenSearch 結合使用。
例如,您可以使用文字表示式語言
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());
| 這些(可移植的)過濾器表示式會自動轉換為專有的 OpenSearch 查詢字串查詢。 |
例如,這個可移植的過濾器表示式
author in ['john', 'jill'] && 'article_type' == 'blog'
轉換為專有的 OpenSearch 過濾器格式
(metadata.author:john OR jill) AND metadata.article_type:blog
訪問原生客戶端
OpenSearch 向量儲存實現透過 getNativeClient() 方法提供對底層原生 OpenSearch 客戶端(OpenSearchClient)的訪問
OpenSearchVectorStore vectorStore = context.getBean(OpenSearchVectorStore.class);
Optional<OpenSearchClient> nativeClient = vectorStore.getNativeClient();
if (nativeClient.isPresent()) {
OpenSearchClient client = nativeClient.get();
// Use the native client for OpenSearch-specific operations
}
原生客戶端允許您訪問 VectorStore 介面可能未公開的 OpenSearch 特定功能和操作。