> ## Documentation Index
> Fetch the complete documentation index at: https://javaai.pig4cloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Weaviate 向量数据库

# Weaviate 向量数据库

Spring AI 支持将 [Weaviate](https://weaviate.io/) 作为向量数据库。

## 添加依赖

要使用 Weaviate 向量存储，您需要将 `spring-ai-weaviate-store-spring-boot-starter` 依赖项添加到项目的 `pom.xml` 文件中。
该启动器包含了 `spring-ai-core` 和 Weaviate Java 客户端库。

```xml theme={"system"}
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-weaviate-store-spring-boot-starter</artifactId>
</dependency>
```

您还需要一个 `EmbeddingClient` 实现来为您的文档生成向量嵌入。例如，您可以添加 `spring-ai-openai-spring-boot-starter` 以使用 OpenAI 的嵌入模型：

```xml theme={"system"}
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
```

## 配置属性

在您的 `application.properties` 或 `application.yml` 文件中配置 Weaviate 和嵌入客户端属性。

### Weaviate 属性

| 属性                                                                | 描述                                                   | 默认值                |
| :---------------------------------------------------------------- | :--------------------------------------------------- | :----------------- |
| `spring.ai.vectorstore.weaviate.scheme`                           | Weaviate 服务器的 scheme (例如 `http` 或 `https`)           | `http`             |
| `spring.ai.vectorstore.weaviate.host`                             | Weaviate 服务器的主机名或 IP 地址                              | `localhost`        |
| `spring.ai.vectorstore.weaviate.api-key`                          | 用于向 Weaviate 服务器进行身份验证的 API 密钥 (如果需要)                |                    |
| `spring.ai.vectorstore.weaviate.object-class`                     | 用于存储文档的 Weaviate 类名                                  | `SpringAiDocument` |
| `spring.ai.vectorstore.weaviate.consistency-level`                | 写入操作的一致性级别 (例如 `ONE`, `QUORUM`, `ALL`)               | `ONE`              |
| `spring.ai.vectorstore.weaviate.headers.*`                        | 要包含在发送到 Weaviate 的请求中的自定义标头                          |                    |
| `spring.ai.vectorstore.weaviate.filter-fields.text-fields`        | 指定哪些元数据文本字段应该被索引以进行 Weaviate 的 `like` 过滤。逗号分隔的列表。    | (空)                |
| `spring.ai.vectorstore.weaviate.filter-fields.tokenizable-fields` | 指定哪些元数据字段应该被索引为 Weaviate 的 `tokenizable` 字段。逗号分隔的列表。 | (空)                |

**示例 `application.properties`:**

```properties theme={"system"}
# Weaviate 配置
spring.ai.vectorstore.weaviate.scheme=http
spring.ai.vectorstore.weaviate.host=localhost:8080 # 假设 Weaviate 在 8080 端口运行
spring.ai.vectorstore.weaviate.object-class=MyDocuments
# spring.ai.vectorstore.weaviate.api-key=YOUR_WEAVIATE_API_KEY # 如果需要

# 嵌入客户端配置 (例如 OpenAI)
spring.ai.openai.api-key=YOUR_OPENAI_API_KEY
spring.ai.openai.embedding.options.model=text-embedding-ada-002
```

<Note>
  嵌入的维度是从第一个插入的文档中推断出来的。确保您的 `EmbeddingClient` 配置为生成具有一致维度的嵌入。
</Note>

## 使用 `VectorStore`

将 `VectorStore` bean 注入到您的组件中以与之交互：

```java theme={"system"}
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.document.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyVectorStoreService {

    private final VectorStore vectorStore; // 将自动配置 WeaviateVectorStore

    @Autowired
    public MyVectorStoreService(VectorStore vectorStore) {
        this.vectorStore = vectorStore;
    }

    public void addDocuments(List<Document> documents) {
        vectorStore.add(documents);
    }

    public List<Document> findSimilarDocuments(String query, int k) {
        return vectorStore.similaritySearch(query, k);
    }
}
```

### 创建 `WeaviateVectorStore` Bean (可选)

Spring Boot 会自动配置 `WeaviateVectorStore` bean。但是，如果您需要自定义配置，可以定义自己的 bean：

```java theme={"system"}
import io.weaviate.client.WeaviateClient;
import io.weaviate.client.Config;
import org.springframework.ai.embedding.EmbeddingClient;
import org.springframework.ai.vectorstore.WeaviateVectorStore;
import org.springframework.ai.vectorstore.WeaviateVectorStore.WeaviateVectorStoreConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Configuration
public class MyWeaviateConfig {

    @Bean
    public WeaviateClient weaviateClient() {
        // 从属性或直接创建 WeaviateClient
        // 例如: new Config("http", "localhost:8080");
        // 如果需要 API 密钥: new Config("https", "your-weaviate-host.com", "YOUR_API_KEY");
        Config config = new Config("http", "localhost:8080");
        return new WeaviateClient(config);
    }

    @Bean
    public WeaviateVectorStore weaviateVectorStore(WeaviateClient weaviateClient, EmbeddingClient embeddingClient) {
        WeaviateVectorStoreConfig config = WeaviateVectorStoreConfig.builder()
            .withObjectClass("MyCustomDocuments")
            // .withConsistencyLevel(WeaviateVectorStoreConfig.ConsistencyLevel.QUORUM) // 按需设置
            // .withHeaders(Map.of("X-Custom-Header", "value")) // 按需设置
            .build();
        return new WeaviateVectorStore(weaviateClient, embeddingClient, config);
    }
}
```

## 元数据过滤

Weaviate 向量存储支持使用 [Weaviate 的 WHERE 过滤器](https://weaviate.io/developers/weaviate/api/graphql/filters) 和 Spring AI 的 [相似性搜索过滤器表达式](./index.mdx#metadata-filtering) 进行元数据过滤。

过滤器表达式会转换为 Weaviate 的 GraphQL `where` 过滤器格式。

**示例：**

```java theme={"system"}
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.filter.Filter;
import org.springframework.ai.vectorstore.filter.FilterExpressionBuilder;

// ...

FilterExpressionBuilder b = new FilterExpressionBuilder();

// path: ["genre"], operator: Equal, valueText: "drama"
// AND path: ["year"], operator: GreaterThan, valueInt: 2020
Filter filter = new Filter(b.eq("genre", "drama").and(b.gt("year", 2020)).build());

SearchRequest request = SearchRequest.query("A dramatic film released after 2020") // 示例查询通常保留英文
    .withTopK(5)
    .withFilter(filter);

List<Document> results = vectorStore.similaritySearch(request);
```

<Note>
  确保用于过滤的元数据字段存在于您的 Weaviate schema 中，并根据需要进行索引。
  对于文本字段的 `like` (通配符) 过滤，您需要在 `spring.ai.vectorstore.weaviate.filter-fields.text-fields` 属性中指定这些字段，以便在 schema 中正确设置它们。
  同样，对于需要标记化的字段，请使用 `spring.ai.vectorstore.weaviate.filter-fields.tokenizable-fields`。
</Note>

## 删除数据

`WeaviateVectorStore` 支持通过文档 ID 删除数据。

```java theme={"system"}
boolean deleted = vectorStore.delete(List.of("documentId1", "documentId2"));
```

## 总结

将 Spring AI 与 Weaviate 集成，为构建复杂的 AI 应用程序提供了强大的功能，利用了 Weaviate 的原生向量搜索能力和可扩展架构。

<Card title="文档有误？请协助编辑" icon="pencil" href="https://github.com/javaai-pig4cloud-com/javaai-docs/edit/main/spring-ai/api/vectordbs/weaviate.mdx">
  发现文档问题？点击此处直接在 GitHub 上编辑并提交 PR，帮助我们改进文档！
</Card>
