Typesense

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

Typesense 是一款开源的容错搜索引擎,专为即时搜索(低于 50 毫秒)优化,同时提供直观的开发者体验。它具备向量搜索功能,使您能够存储并查询高维向量,与常规搜索数据并行处理。

先决条件

  • 一个正在运行的 Typesense 实例。以下选项可供选择:
  • 如需要,可为 EmbeddingModel 提供 API 密钥,以生成由 TypesenseVectorStore 存储的嵌入。

自动配置

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'
}

向量存储实现可以为您初始化必要的架构,但您需通过在 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

属性 (Property) 描述 (Description) 默认值 (Default Value)
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 密钥 xyz

手动配置

您可以选择手动配置 Typesense 向量存储,而非依赖 Spring Boot 的自动配置。为此,需在项目中添加 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'
}

创建 Typesense 客户端 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());

例如这个便携式过滤器表达式:

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

作者:Jeebiz  创建时间:2025-08-03 12:10
最后编辑:Jeebiz  更新时间:2025-09-28 09:15