Weaviate

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

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

Weaviate 是一个开源的向量数据库,支持存储来自各类机器学习模型的数据对象和向量嵌入,并能无缝扩展至数十亿数据对象。它提供存储文档嵌入、内容和元数据的工具,以及搜索这些嵌入(包括元数据过滤)的功能。

先决条件

依赖

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

在项目中添加 Weaviate 向量存储依赖:

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

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

dependencies {
    implementation 'org.springframework.ai:spring-ai-weaviate-store'
}
参考 “依赖管理” 章节将 Spring AI BOM 添加至构建文件。

配置

要连接 Weaviate 并使用 WeaviateVectorStore,需提供实例的访问参数。可通过 Spring Boot 的 application.properties 文件进行配置。

spring.ai.vectorstore.weaviate.host=<host_of_your_weaviate_instance>
spring.ai.vectorstore.weaviate.scheme=<http_or_https>
spring.ai.vectorstore.weaviate.api-key=<your_api_key>
# API key if needed, e.g. OpenAI
spring.ai.openai.api-key=<api-key>

若倾向对 API Key 等敏感信息使用环境变量,可通过以下方式配置:

选项 1:使用 Spring 表达式语言(SpEL)

可以在应用配置中引用自定义环境变量名:

# In application.yml
spring:
  ai:
    vectorstore:
      weaviate:
        host: ${WEAVIATE_HOST}
        scheme: ${WEAVIATE_SCHEME}
        api-key: ${WEAVIATE_API_KEY}
    openai:
      api-key: ${OPENAI_API_KEY}
# In your environment or .env file
export WEAVIATE_HOST=<host_of_your_weaviate_instance>
export WEAVIATE_SCHEME=<http_or_https>
export WEAVIATE_API_KEY=<your_api_key>
export OPENAI_API_KEY=<api-key>

选项 2:通过编程方式访问环境变量

或者,可以在 Java 代码中访问环境变量:

String weaviateApiKey = System.getenv("WEAVIATE_API_KEY");
String openAiApiKey = System.getenv("OPENAI_API_KEY");
如果你选择创建一个 shell 脚本来管理你的环境变量,请确保在启动应用之前通过 source 该文件来执行它,例如:source <你的脚本名>.sh

自动配置

Spring AI 为 Weaviate 向量存储提供 Spring Boot 自动配置。要启用该功能,请在项目的 Maven pom.xml 文件中添加以下依赖。

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

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

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-weaviate'
}
参考 “依赖管理” 章节将 Spring AI BOM 添加至构建文件。

请查看向量存储的 配置参数列表 以了解默认值及可配置选项。

参考 “构件仓库” 章节将 Maven Central 和/或 Snapshot Repositories 添加至构建文件。

此外,还需配置一个 EmbeddingModel Bean。详情请参阅 EmbeddingModel 部分。

以下是所需 Bean 的示例:

@Bean
public EmbeddingModel embeddingModel() {
    // Retrieve API key from a secure source or environment variable
    String apiKey = System.getenv("OPENAI_API_KEY");

    // Can be any other EmbeddingModel implementation
    return new OpenAiEmbeddingModel(OpenAiApi.builder().apiKey(apiKey).build());
}

现在你可以在应用中将 WeaviateVectorStore 自动注入为一个向量存储。

手动配置

除了使用 Spring Boot 的自动配置外,你也可以通过 Builder 模式手动配置 WeaviateVectorStore

@Bean
public WeaviateClient weaviateClient() {
    return new WeaviateClient(new Config("http", "localhost:8080"));
}

@Bean
public VectorStore vectorStore(WeaviateClient weaviateClient, EmbeddingModel embeddingModel) {
    return WeaviateVectorStore.builder(weaviateClient, embeddingModel)
        .objectClass("CustomClass")                    // Optional: defaults to "SpringAiWeaviate"
        .consistencyLevel(ConsistentLevel.QUORUM)      // Optional: defaults to ConsistentLevel.ONE
        .filterMetadataFields(List.of(                 // Optional: fields that can be used in filters
            MetadataField.text("country"),
            MetadataField.number("year")))
        .build();
}

元数据过滤

你同样可以将通用的、可移植的 元数据过滤器 与 Weaviate 存储一起使用。

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

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());
这些(可移植的)过滤器表达式会自动转换为 Weaviate 专有的 where 过滤器

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

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

会被转换为 Weaviate 专有的 GraphQL 过滤器格式:

operator: And
operands:
    [{
        operator: Or
        operands:
            [{
                path: ["meta_country"]
                operator: Equal
                valueText: "UK"
            },
            {
                path: ["meta_country"]
                operator: Equal
                valueText: "NL"
            }]
    },
    {
        path: ["meta_year"]
        operator: GreaterThanEqual
        valueNumber: 2020
    }]

在 Docker 中运行 Weaviate

要快速开始使用本地的 Weaviate 实例,你可以在 Docker 中运行它:

docker run -it --rm --name weaviate \
    -e AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED=true \
    -e PERSISTENCE_DATA_PATH=/var/lib/weaviate \
    -e QUERY_DEFAULTS_LIMIT=25 \
    -e DEFAULT_VECTORIZER_MODULE=none \
    -e CLUSTER_HOSTNAME=node1 \
    -p 8080:8080 \
    semitechnologies/weaviate:1.22.4

这将启动一个可通过 localhost:8080 访问的 Weaviate 实例。

WeaviateVectorStore 配置属性

你可以在 Spring Boot 配置中使用以下属性来自定义 Weaviate 向量存储。

属性 说明 默认值

spring.ai.vectorstore.weaviate.host

Weaviate 服务器的主机

localhost:8080

spring.ai.vectorstore.weaviate.scheme

连接协议(schema)

http

spring.ai.vectorstore.weaviate.api-key

API key

spring.ai.vectorstore.weaviate.object-class

用于存储文档的类名

SpringAiWeaviate

spring.ai.vectorstore.weaviate.consistency-level

在一致性与速度之间的期望权衡

ConsistentLevel.ONE

spring.ai.vectorstore.weaviate.filter-field

配置可用于过滤器的元数据字段。格式:spring.ai.vectorstore.weaviate.filter-field.<字段名>=<字段类型>

访问原生客户端

Weaviate 向量存储实现通过 getNativeClient() 方法提供对底层原生 Weaviate 客户端(WeaviateClient)的访问:

WeaviateVectorStore vectorStore = context.getBean(WeaviateVectorStore.class);
Optional<WeaviateClient> nativeClient = vectorStore.getNativeClient();

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

原生客户端让你可以访问 VectorStore 接口可能未暴露的 Weaviate 特定功能和操作。