> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/rag-yu-xiang-liang-shu-ju-ku/weaviate.md).

# Weaviate

{% hint style="info" %}
**Weaviate** 是一个 AI 原生、开源的向量数据库，专为语义搜索、混合搜索和 RAG（检索增强生成）应用而设计。它同时存储对象及其向量嵌入，并支持内置的机器学习模型集成。
{% endhint %}

## 概览

Weaviate 通过在导入和查询时原生集成机器学习模型进行自动向量化，从而超越了传统向量数据库。它支持多种数据类型（文本、图片、视频、音频）、内置结合 BM25 与向量相似度的混合搜索，以及多租户部署。Weaviate 已可用于生产环境，云原生设计，可从原型扩展到数十亿级向量。

| 属性            | 数值                                                        |
| ------------- | --------------------------------------------------------- |
| **类别**        | 向量数据库 / RAG 基础设施                                          |
| **开发者**       | Weaviate B.V.                                             |
| **许可证**       | BSD 3-Clause                                              |
| **GitHub**    | [weaviate/weaviate](https://github.com/weaviate/weaviate) |
| **星标**        | 12K+                                                      |
| **Docker 镜像** | `cr.weaviate.io/semitechnologies/weaviate`                |
| **端口**        | 22（SSH）、8080（HTTP API / GraphQL）                          |

***

## 主要特性

* **向量 + 关键词混合搜索** —— 在一次查询中结合 BM25 全文检索与向量相似度
* **内置向量化器** —— 在导入时使用 OpenAI、Cohere、HuggingFace 或本地模型自动向量化数据
* **多模态** —— 在一个数据库中存储和搜索文本、图片、视频、音频
* **GraphQL API** —— 用于复杂语义查询的表达式查询语言
* **REST API** —— 完整的 CRUD 操作和模式管理
* **多租户** —— 在共享基础设施下按租户隔离数据
* **HNSW 索引** —— 快速近似最近邻搜索
* **过滤搜索** —— 将向量搜索与传统元数据过滤条件结合
* **生成式搜索** —— 与 LLM 集成的内置 RAG
* **水平扩展** —— 在多个节点之间分片并复制
* **模块系统** —— 插入向量化器、读取器、生成器

***

## Clore.ai 设置

### 步骤 1 — 选择硬件

| 使用场景              | 推荐       | 内存     | 存储      |
| ----------------- | -------- | ------ | ------- |
| 开发 / 原型设计         | CPU 实例   | 8 GB   | 20 GB   |
| 小型生产环境（< 100 万向量） | CPU 实例   | 16 GB  | 50 GB   |
| 大规模（1000 万+ 向量）   | GPU 实例   | 32 GB+ | 200 GB+ |
| GPU 加速向量化         | RTX 4090 | 24 GB  | 100 GB  |

{% hint style="info" %}
Weaviate 本身运行在 CPU 上。当你需要 **本地嵌入模型** 推理（例如 `text2vec-transformers` 配合本地模型）进行导入时的快速向量化。
{% endhint %}

### 步骤 2 — 在 Clore.ai 上租用服务器

1. 前往 [clore.ai](https://clore.ai) → **市场**
2. 对于纯向量搜索：带有以下配置的 CPU 实例 **≥ 16 GB 内存**
3. 对于 GPU 加速的嵌入： **RTX 3090 或 4090**
4. 开放端口： **22** 以及 **8080**
5. 确保 **≥ 50 GB 磁盘** 用于向量存储

### 步骤 3 — 使用 Docker 部署

**最小化部署（无向量化器）：**

```bash
docker run -d \\
    --name weaviate \
    -p 8080:8080 \\
    -p 50051:50051 \
    -v /opt/weaviate/data:/var/lib/weaviate \
    -e QUERY_DEFAULTS_LIMIT=20 \
    -e AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED=true \
    -e PERSISTENCE_DATA_PATH=/var/lib/weaviate \
    -e DEFAULT_VECTORIZER_MODULE=none \
    -e ENABLE_MODULES="" \
    -e CLUSTER_HOSTNAME=node1 \
    cr.weaviate.io/semitechnologies/weaviate:latest
```

**使用 OpenAI 向量化器：**

```bash
docker run -d \\
    --name weaviate \
    -p 8080:8080 \\
    -v /opt/weaviate/data:/var/lib/weaviate \
    -e QUERY_DEFAULTS_LIMIT=20 \
    -e AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED=true \
    -e PERSISTENCE_DATA_PATH=/var/lib/weaviate \
    -e DEFAULT_VECTORIZER_MODULE=text2vec-openai \
    -e ENABLE_MODULES=text2vec-openai,generative-openai \
    -e OPENAI_APIKEY=<your-openai-key> \
    -e CLUSTER_HOSTNAME=node1 \
    cr.weaviate.io/semitechnologies/weaviate:latest
```

**使用本地 HuggingFace 向量化器（GPU 加速）：**

```yaml
# docker-compose.yml
version: '3.4'

services:
  weaviate:
    image: cr.weaviate.io/semitechnologies/weaviate:latest
    restart: unless-stopped
    ports:
      - "8080:8080"
      - "50051:50051"
    volumes:
      - /opt/weaviate/data:/var/lib/weaviate
    environment:
      QUERY_DEFAULTS_LIMIT: 20
      AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED: 'true'
      PERSISTENCE_DATA_PATH: '/var/lib/weaviate'
      DEFAULT_VECTORIZER_MODULE: text2vec-transformers
      ENABLE_MODULES: 'text2vec-transformers,generative-openai'
      TRANSFORMERS_INFERENCE_API: 'http://t2v-transformers:8080'
      CLUSTER_HOSTNAME: 'node1'

  t2v-transformers:
    image: cr.weaviate.io/semitechnologies/transformers-inference:sentence-transformers-multi-qa-MiniLM-L6-cos-v1
    environment:
      ENABLE_CUDA: '1'
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              数量：1
              capabilities: [gpu]
```

开始：

```bash
mkdir -p /opt/weaviate/data
docker-compose up -d
```

***

## 访问 API

### HTTP/REST API

```
http://<server-ip>:8080
```

### GraphQL 端点

```
http://<server-ip>:8080/v1/graphql
```

### 健康检查

```bash
curl http://<server-ip>:8080/v1/.well-known/ready
# 返回：{}（HTTP 200 = 正常）
```

### 通过 SSH

```bash
ssh root@<server-ip> -p 22
```

***

## Python 客户端

### 安装

```bash
pip install weaviate-client
```

### 连接

```python
import weaviate
import weaviate.classes as wvc

# 连接到你的 Clore.ai 实例
client = weaviate.connect_to_custom(
    http_host="<server-ip>",
    http_port=8080,
    http_secure=False,
    grpc_host="<server-ip>",
    grpc_port=50051,
    grpc_secure=False,
)

print(client.is_ready())  # 正常则为 True
```

***

## 模式与集合

### 创建集合

```python
import weaviate
import weaviate.classes as wvc
from weaviate.classes.config import Configure, Property, DataType

client = weaviate.connect_to_custom(
    http_host="<server-ip>", http_port=8080,
    grpc_host="<server-ip>", grpc_port=50051,
    http_secure=False, grpc_secure=False,
)

# 创建一个集合（在 v3 中称为 "class"）
client.collections.create(
    name="Article",
    vectorizer_config=Configure.Vectorizer.none(),  # 我们将提供自己的向量
    # 或：Configure.Vectorizer.text2vec_openai() 用于自动向量化
    properties=[
        Property(name="title", data_type=DataType.TEXT),
        Property(name="content", data_type=DataType.TEXT),
        Property(name="author", data_type=DataType.TEXT),
        Property(name="published_date", data_type=DataType.DATE),
        Property(name="tags", data_type=DataType.TEXT_ARRAY),
        Property(name="view_count", data_type=DataType.INT),
    ],
)
print("集合 'Article' 已创建")
```

***

## 导入数据

### 使用预计算向量批量导入

```python
import weaviate
import numpy as np
from sentence_transformers import SentenceTransformer

client = weaviate.connect_to_custom(
    http_host="<server-ip>", http_port=8080,
    grpc_host="<server-ip>", grpc_port=50051,
    http_secure=False, grpc_secure=False,
)

# 加载嵌入模型
encoder = SentenceTransformer("all-MiniLM-L6-v2")

# 示例文章
articles = [
    {"title": "RAG 入门", "content": "RAG 将检索与生成结合……"},
    {"title": "向量数据库详解", "content": "向量数据库存储高维嵌入……"},
    {"title": "Weaviate 最佳实践", "content": "对于生产环境中的 Weaviate 部署，请考虑……"},
    {"title": "GPU 云计算", "content": "Clore.ai 提供去中心化的 GPU 访问……"},
]

# 使用向量批量导入
collection = client.collections.get("Article")

with collection.batch.dynamic() as batch:
    for article in articles:
        # 计算向量
        vector = encoder.encode(article["content"]).tolist()

        batch.add_object(
            properties={
                "title": article["title"],
                "content": article["content"],
            },
            vector=vector,
        )

print(f"已导入 {len(articles)} 篇文章")
```

### 使用 OpenAI 自动向量化（导入时）

```python
# 当集合使用 text2vec-openai 向量化器时，
# 只需插入数据——不需要向量
collection = client.collections.get("ArticleOpenAI")

with collection.batch.dynamic() as batch:
    for article in articles:
        batch.add_object(
            properties={
                "title": article["title"],
                "content": article["content"],
            }
            # 无需向量 = Weaviate 通过 OpenAI 自动向量化
        )
```

***

## 查询

### 语义（向量）搜索

```python
# 查找与查询语义相似的文章
results = collection.query.near_text(
    query="如何高效存储嵌入",
    limit=5,
    return_properties=["title", "content"],
    return_metadata=wvc.query.MetadataQuery(distance=True),
)

for obj in results.objects:
    print(f"标题：{obj.properties['title']}")
    print(f"距离：{obj.metadata.distance:.4f}")
    print()
```

### 混合搜索（向量 + BM25）

```python
# 结合语义搜索和关键词搜索
results = collection.query.hybrid(
    query="RAG 检索增强生成",
    alpha=0.5,  # 0.0 = 纯 BM25，1.0 = 纯向量，0.5 = 平衡
    limit=5,
    return_properties=["title", "content"],
    return_metadata=wvc.query.MetadataQuery(score=True),
)

for obj in results.objects:
    print(f"标题：{obj.properties['title']}")
    print(f"混合得分：{obj.metadata.score:.4f}")
```

### 关键词搜索（BM25）

```python
results = collection.query.bm25(
    query="向量数据库索引",
    limit=5,
    return_properties=["title"],
)
```

### 过滤搜索

```python
from weaviate.classes.query import Filter

# 将向量搜索与元数据过滤结合
results = collection.query.near_text(
    query="机器学习训练",
    limit=10,
    filters=Filter.by_property("view_count").greater_than(1000),
    return_properties=["title", "view_count"],
)
```

### GraphQL 查询

```python
import requests

query = """
{
    Get {
        Article(
            nearText: {concepts: ["人工智能"]}
            limit: 5
        ) {
            title
            content
            _additional {
                distance
                id
            }
        }
    }
}
"""

response = requests.post(
    "http://<server-ip>:8080/v1/graphql",
    json={"query": query},
)
data = response.json()
for article in data["data"]["Get"]["Article"]:
    print(article["title"])
```

***

## 生成式搜索（RAG）

```python
from weaviate.classes.generate import GenerateOptions

# 配置带生成模块的集合（OpenAI）
# 需要 ENABLE_MODULES=generative-openai

results = collection.generate.near_text(
    query="如何构建 RAG 系统",
    limit=3,
    grouped_task="总结这些文章，并解释构建 RAG 系统的关键步骤。",
    grouped_properties=["title", "content"],
)

print("RAG 答案：")
print(results.generated)
print("\n源文章：")
for obj in results.objects:
    print(f"  - {obj.properties['title']}")
```

***

## 多租户

```python
from weaviate.classes.config import Configure

# 创建多租户集合
client.collections.create(
    name="UserDocuments",
    multi_tenancy_config=Configure.multi_tenancy(enabled=True),
    properties=[
        Property(name="content", data_type=DataType.TEXT),
        Property(name="filename", data_type=DataType.TEXT),
    ],
)

# 创建租户
collection = client.collections.get("UserDocuments")
collection.tenants.create([
    wvc.config.Tenant(name="user_alice"),
    wvc.config.Tenant(name="user_bob"),
])

# 为特定租户插入数据
tenant_collection = collection.with_tenant("user_alice")
tenant_collection.data.insert({"content": "Alice 的私有文档", "filename": "doc1.pdf"})

# 在租户内查询
results = collection.with_tenant("user_alice").query.near_text(
    query="私有文档",
    limit=5,
)
```

***

## REST API 示例

```bash
# 创建 schema 类
curl -X POST http://<server-ip>:8080/v1/schema \
    -H "Content-Type: application/json" \\
    -d '{
        "class": "Product",
        "vectorizer": "none",
        "properties": [
            {"name": "name", "dataType": ["text"]},
            {"name": "description", "dataType": ["text"]},
            {"name": "price", "dataType": ["number"]}
        ]
    }'

# 添加带向量的对象
curl -X POST http://<server-ip>:8080/v1/objects \
    -H "Content-Type: application/json" \\
    -d '{
        "class": "Product",
        "properties": {
            "name": "GPU 云访问",
            "description": "去中心化 GPU 市场",
            "price": 0.5
        },
        "vector": [0.1, 0.2, 0.3, ...]
    }'

# 向量搜索
curl http://<server-ip>:8080/v1/objects?class=Product&limit=5

# 健康检查
curl http://<server-ip>:8080/v1/.well-known/ready
```

***

## 故障排查

{% hint style="warning" %}
**Weaviate 无法启动** —— 检查磁盘空间（`df -h`）。Weaviate 需要在数据路径上有可写空间。另请确认 Clore.ai 设置中端口 8080 已开放。
{% endhint %}

{% hint style="warning" %}
**导入缓慢** —— 启用批量导入（`collection.batch.dynamic()` 或 `fixed_size()`）。大型数据集避免单对象导入。批量大小 100–500 效果最佳。
{% endhint %}

{% hint style="info" %}
**内存占用高** —— 为了快速搜索，Weaviate 会将向量索引保留在 RAM 中。对于 100 万个 768 维向量：约 6 GB RAM。选择 Clore.ai 实例规格时请据此规划。
{% endhint %}

{% hint style="info" %}
**无法通过 Python 客户端连接** —— 确保端口 8080（HTTP）和 50051（gRPC）都已开放。v4 Python 客户端默认使用 gRPC。
{% endhint %}

| 问题           | 修复                                         |
| ------------ | ------------------------------------------ |
| `连接被拒绝`      | 等待启动（约 30 秒），检查 `docker ps`，验证端口           |
| `Schema 已存在` | 先删除集合： `client.collections.delete("Name")` |
| `内存不足`       | 增加内存或减少向量维度                                |
| 向量搜索缓慢       | 添加 HNSW 索引，或检查数据集大小与可用 RAM 是否匹配            |

***

## 性能提示

1. **使用批量导入** —— 比单条插入快 10x–50x
2. **选择合适的嵌入模型** — `all-MiniLM-L6-v2` （384 维）速度很快； `text-embedding-3-large` （3072 维）质量最佳，但会多占用 8 倍 RAM
3. **混合搜索 alpha** —— 调整 `alpha` 以适配你的使用场景：关键词密集查询用 0.25，语义查询用 0.75
4. **HNSW 参数** — `ef` 以及 `efConstruction` 控制召回率与速度之间的权衡
5. **租户隔离** —— SaaS 应用使用多租户；它比按用户单独建集合更具扩展性

***

## 相关工具

* [Qdrant](/guides/guides_v2-zh/rag-yu-xiang-liang-shu-ju-ku/qdrant.md) —— 基于 Rust 的向量数据库，支持载荷过滤
* [ChromaDB](/guides/guides_v2-zh/rag-yu-xiang-liang-shu-ju-ku/chromadb.md) —— 轻量级嵌入数据库
* [Milvus](/guides/guides_v2-zh/rag-yu-xiang-liang-shu-ju-ku/milvus.md) —— 大规模向量数据库

***

*Clore.ai 上的 Weaviate 为你提供生产级向量数据库与 GPU 加速向量化——非常适合构建可扩展的 RAG 系统和语义搜索应用。*

***

## Clore.ai GPU 推荐

| 使用场景    | 推荐 GPU         | Clore.ai 预计成本     |
| ------- | -------------- | ----------------- |
| 开发/测试   | RTX 3090（24GB） | $0.07–0.21/gpu/hr |
| 生产级向量搜索 | RTX 3090（24GB） | $0.07–0.21/gpu/hr |
| 高吞吐量嵌入  | RTX 4090（24GB） | $0.14–0.42/gpu/hr |

> 💡 本指南中的所有示例都可以部署在 [Clore.ai](https://clore.ai/marketplace) GPU 服务器上。浏览可用 GPU 并按小时租用——无需承诺，拥有完整 root 访问权限。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/rag-yu-xiang-liang-shu-ju-ku/weaviate.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
