Typesense

本節將引導您設定 TypesenseVectorStore 來儲存文件嵌入並執行相似性搜尋。

Typesense 是一個開源的、支援拼寫容錯的搜尋引擎,經過最佳化可實現低於 50 毫秒的即時搜尋,同時提供直觀的開發體驗。它提供向量搜尋功能,允許您將高維向量與常規搜尋資料一起儲存和查詢。

先決條件

  • 執行中的 Typesense 例項。以下選項可用

  • 如果需要,用於生成由 TypesenseVectorStore 儲存的嵌入的 EmbeddingModel 的 API 金鑰。

自動配置

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

Spring AI 為 Typesense Vector Store 提供 Spring Boot 自動配置。要啟用它,請將以下依賴項新增到專案的 Maven pom.xml 檔案中

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

或新增到您的 Gradle build.gradle 構建檔案中。

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-typesense'
}
請參閱依賴管理部分,將 Spring AI BOM 新增到您的構建檔案中。

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

請參閱倉庫部分,將 Maven Central 和/或 Snapshot 倉庫新增到您的構建檔案中。

向量儲存實現可以為您初始化所需的 schema,但您必須在 application.properties 檔案中設定 …​initialize-schema=true 來啟用此功能。

此外,您還需要配置一個 EmbeddingModel bean。更多資訊請參考EmbeddingModel部分。

現在您可以在應用程式中透過自動注入將 TypesenseVectorStore 用作向量儲存

@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 Typesense
vectorStore.add(documents);

// Retrieve documents similar to a query
List<Document> results = vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());

配置屬性

要連線到 Typesense 並使用 TypesenseVectorStore,您需要提供例項的訪問詳細資訊。可以透過 Spring Boot 的 application.yml 提供簡單的配置

spring:
  ai:
    vectorstore:
      typesense:
        initialize-schema: true
        collection-name: vector_store
        embedding-dimension: 1536
        client:
          protocol: http
          host: localhost
          port: 8108
          api-key: xyz

spring.ai.vectorstore.typesense.* 開頭的屬性用於配置 TypesenseVectorStore

屬性 描述 預設值

spring.ai.vectorstore.typesense.initialize-schema

是否初始化所需的 schema

false

spring.ai.vectorstore.typesense.collection-name

儲存向量的 collection 名稱

vector_store

spring.ai.vectorstore.typesense.embedding-dimension

向量的維度數量

1536

spring.ai.vectorstore.typesense.client.protocol

HTTP 協議

http

spring.ai.vectorstore.typesense.client.host

主機名

localhost

spring.ai.vectorstore.typesense.client.port

8108

spring.ai.vectorstore.typesense.client.api-key

spring.ai.vectorstore.typesense.client.api-key

API 金鑰

手動配置

除了使用 Spring Boot 自動配置外,您還可以手動配置 Typesense 向量儲存。為此,您需要將 spring-ai-typesense-store 新增到您的專案中

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-typesense-store</artifactId>
</dependency>

或新增到您的 Gradle build.gradle 構建檔案中。

dependencies {
    implementation 'org.springframework.ai:spring-ai-typesense-store'
}
請參閱依賴管理部分,將 Spring AI BOM 新增到您的構建檔案中。

建立 Typesense Client bean

@Bean
public Client typesenseClient() {
    List<Node> nodes = new ArrayList<>();
    nodes.add(new Node("http", "localhost", "8108"));
    Configuration configuration = new Configuration(nodes, Duration.ofSeconds(5), "xyz");
    return new Client(configuration);
}

然後使用構建器模式建立 TypesenseVectorStore bean

@Bean
public VectorStore vectorStore(Client client, EmbeddingModel embeddingModel) {
    return TypesenseVectorStore.builder(client, embeddingModel)
        .collectionName("custom_vectors")     // Optional: defaults to "vector_store"
        .embeddingDimension(1536)            // Optional: defaults to 1536
        .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")));
}

元資料過濾

您也可以在 Typesense 儲存中使用通用的可移植元資料過濾器

例如,您可以使用文字表示式語言

vectorStore.similaritySearch(
    SearchRequest.builder()
        .query("The World")
        .topK(TOP_K)
        .similarityThreshold(SIMILARITY_THRESHOLD)
        .filterExpression("country in ['UK', 'NL'] && year >= 2020").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("country", "UK", "NL"),
        b.gte("year", 2020)).build()).build());
這些(可移植的)過濾表示式會自動轉換為Typesense 搜尋過濾器

例如,此可移植過濾表示式

country in ['UK', 'NL'] && year >= 2020

將轉換為 Typesense 專有的過濾格式

country: ['UK', 'NL'] && year: >=2020

如果您檢索文件的順序不符合預期或搜尋結果不符合預期,請檢查您正在使用的嵌入模型。

嵌入模型對搜尋結果有重大影響(例如,如果您的資料是西班牙語,請確保使用西班牙語或多語言嵌入模型)。

訪問原生客戶端

Typesense Vector Store 實現透過 getNativeClient() 方法提供對底層原生 Typesense 客戶端 (Client) 的訪問

TypesenseVectorStore vectorStore = context.getBean(TypesenseVectorStore.class);
Optional<Client> nativeClient = vectorStore.getNativeClient();

if (nativeClient.isPresent()) {
    Client client = nativeClient.get();
    // Use the native client for Typesense-specific operations
}

原生客戶端允許您訪問 Typesense 特定的功能和操作,這些功能和操作可能不會透過 VectorStore 介面公開。