Typesense

本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。

本节将指导你设置 TypesenseVectorStore 用于存储文档嵌入并执行相似性搜索。

Typesense 是一个开源的容错搜索引擎,针对 50 毫秒内的即时搜索进行了优化,同时提供直观的开发者体验。它支持向量搜索功能,允许你在常规搜索数据旁存储和查询高维向量。

先决条件

  • 一个正在运行的 Typesense 实例。可用选项包括:

  • 如需生成 TypesenseVectorStore 存储的嵌入向量,需为 EmbeddingModel 配置 API 密钥。

自动配置

Spring AI 的自动配置及 Starter 模块的构件名称发生重大变更。详情请查阅 升级说明

Spring AI 为 Typesense 向量存储提供 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 Repositories 添加至构建文件。

向量存储实现可以为你初始化所需 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

用于存储向量的集合名称

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

API Key

xyz

手动配置

若不使用 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 添加至构建文件。

创建 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);
}

随后通过 Builder 模式创建 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 向量存储实现通过 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
}

原生客户端使你可以访问 VectorStore 接口可能未暴露的、Typesense 特有的功能和操作。