OpenSearch

本節將引導您完成 OpenSearchVectorStore 的設定,以便儲存文件嵌入並執行相似度搜索。

OpenSearch 是一個開源搜尋和分析引擎,最初從 Elasticsearch 分支而來,根據 Apache License 2.0 釋出。它透過簡化 AI 生成資產的整合和管理,增強了 AI 應用開發。OpenSearch 支援向量、詞法和混合搜尋功能,利用先進的向量資料庫功能來促進低延遲查詢和相似度搜索,詳情請參閱向量資料庫頁面

OpenSearch k-NN 功能允許使用者查詢大型資料集中的向量嵌入。嵌入是資料物件(如文字、影像、音訊或文件)的數值表示。嵌入可以儲存在索引中,並使用各種相似度函式進行查詢。

先決條件

自動配置

Spring AI 自動配置、starter 模組的 artifact 名稱發生了重大變化。更多資訊請參考升級說明

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'
}
請參閱依賴管理部分,瞭解如何將 Spring AI BOM 新增到您的構建檔案中。

對於 Amazon OpenSearch 服務,請改用這些依賴項:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-vector-store-opensearch</artifactId>
</dependency>

或對於 Gradle:

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-opensearch'
}

請查看向量儲存的配置引數列表,以瞭解預設值和配置選項。

此外,您還需要配置一個 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
        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

屬性 描述 預設值

spring.ai.vectorstore.opensearch.uris

OpenSearch 叢集端點的 URI

-

spring.ai.vectorstore.opensearch.username

訪問 OpenSearch 叢集的使用者名稱

-

spring.ai.vectorstore.opensearch.password

指定使用者名稱的密碼

-

spring.ai.vectorstore.opensearch.index-name

儲存向量的索引名稱

spring-ai-document-index

spring.ai.vectorstore.opensearch.initialize-schema

是否初始化所需模式

false

spring.ai.vectorstore.opensearch.similarity-function

要使用的相似度函式

cosinesimil

spring.ai.vectorstore.opensearch.aws.host

OpenSearch 例項的主機名

-

spring.ai.vectorstore.opensearch.aws.service-name

AWS 服務名稱

-

spring.ai.vectorstore.opensearch.aws.access-key

AWS 訪問金鑰

-

spring.ai.vectorstore.opensearch.aws.secret-key

AWS 秘密金鑰

-

spring.ai.vectorstore.opensearch.aws.region

AWS 區域

-

以下相似度函式可用:

  • cosinesimil - 預設值,適用於大多數用例。衡量向量之間的餘弦相似度。

  • l1 - 向量之間的曼哈頓距離。

  • l2 - 向量之間的歐幾里得距離。

  • linf - 向量之間的切比雪夫距離。

手動配置

您也可以手動配置 OpenSearch 向量儲存,而不是使用 Spring Boot 自動配置。為此,您需要將 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()));
}

然後使用 Builder 模式建立 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"
        .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

_json_filter({"bool":{"must":[{"term":{"metadata.document_id":"doc1"}}]}})

訪問原生客戶端

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
}

OpenSearch 向量儲存實現透過 getNativeClient() 方法提供了對底層原生 OpenSearch 客戶端 (OpenSearchClient) 的訪問: