Skip to content
Spring AI 文档版本 2.1.0-SNAPSHOT 源快照 34d70e32 更新于 2026-10-16

Typesense

本节引导你设置 TypesenseVectorStore 以存储文档嵌入并执行相似度搜索。

Typesense 是一个开源的、容错的拼写纠错搜索引擎,针对即时的 50 毫秒以下搜索做了优化,同时提供直观的开发者体验。它提供向量搜索能力,让你能在常规搜索数据旁存储并查询高维向量。

前置条件

  • 一个正在运行的 Typesense 实例。有以下可选方案:
  • 如有需要,为 EmbeddingModel 配置一个 API 密钥,以生成 TypesenseVectorStore 所存储的嵌入。

自动配置

NOTE

Spring AI 的自动配置、starter 模块的制品名称发生了重大变更。 更多信息请参阅 升级说明。

Spring AI 为 Typesense 向量库提供 Spring Boot 自动配置。 要启用它,请将以下依赖添加到你的项目的 Maven pom.xml 文件:

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

或添加到你的 Gradle build.gradle 构建文件。

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

TIP

参见 依赖管理 一节,把 Spring AI BOM 添加到你的构建文件。

请查看该向量库的配置参数列表,了解默认值和配置选项。

TIP

参见 制品仓库 一节,把 Maven Central 和/或 Snapshot 仓库添加到你的构建文件。

向量库实现可以为你初始化所需的模式,但你必须显式开启,方法是在 application.properties 文件中设置 ...initialize-schema=true。

此外,你还需要一个已配置的 EmbeddingModel bean。更多信息参见 EmbeddingModel 一节。

现在你可以在应用中把 TypesenseVectorStore 作为向量库自动装配:

java
@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 提供:

yaml
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是否初始化所需的模式false
spring.ai.vectorstore.typesense.collection-name存储向量的集合名vector_store
spring.ai.vectorstore.typesense.embedding-dimension向量的维度数1536
spring.ai.vectorstore.typesense.client.protocolHTTP 协议http
spring.ai.vectorstore.typesense.client.host主机名localhost
spring.ai.vectorstore.typesense.client.port端口8108
spring.ai.vectorstore.typesense.client.api-keyAPI 密钥xyz

手动配置

与其使用 Spring Boot 自动配置,不如手动配置 Typesense 向量库。为此你需要把 spring-ai-typesense-store 添加到你的项目:

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

或添加到你的 Gradle build.gradle 构建文件。

groovy
dependencies {
    implementation 'org.springframework.ai:spring-ai-typesense-store'
}

TIP

参见 依赖管理 一节,把 Spring AI BOM 添加到你的构建文件。

创建一个 Typesense Client bean:

java
@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:

java
@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(OpenAiEmbeddingOptions.builder().apiKey(System.getenv("OPENAI_API_KEY")).build());
}

元数据过滤

你也可以在 Typesense 向量库上利用通用、可移植的元数据过滤器。

例如,你可以使用文本表达式语言:

java
vectorStore.similaritySearch(
    SearchRequest.builder()
        .query("The World")
        .topK(TOP_K)
        .similarityThreshold(SIMILARITY_THRESHOLD)
        .filterExpression("country in ['UK', 'NL'] && year >= 2020").build());

或以编程方式使用 Filter.Expression DSL:

java
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());

NOTE

这些(可移植的)过滤表达式会被自动转换为 Typesense 搜索过滤器。

例如这个可移植的过滤表达式:

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

会被转换为 Typesense 专有的过滤格式:

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

NOTE

如果你没能按预期顺序取回文档,或搜索结果不符合预期,请检查你所使用的嵌入模型。 嵌入模型会对搜索结果产生重大影响(也就是说,如果你的数据是西班牙语的,务必使用西班牙语或多语种的嵌入模型)。

访问原生客户端

Typesense 向量库实现通过 getNativeClient() 方法提供对底层原生 Typesense 客户端(Client)的访问:

java
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 特定功能与操作。

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。