跳转至

Weaviate 向量搜索

为什么要学 Weaviate

Weaviate 是一个云原生的开源向量数据库,专注于大规模语义搜索和 AI 应用。它不仅存储向量,还原生支持混合搜索(向量 + 关键词)、自动向量化、多模态数据和 GraphQL API。对于需要构建生产级搜索和 RAG 系统的团队来说,Weaviate 提供了比 Chroma 更强的扩展性和更丰富的查询能力。


核心概念

概念白话解释用途
Class类/集合存储同类对象的容器(类似数据库表)
Object对象一条数据记录(含属性和向量)
Schema模式定义数据结构和索引方式
Module模块可插拔的功能扩展(向量化、搜索等)
Hybrid Search混合搜索结合向量搜索和关键词搜索
Multi-tenancy多租户数据隔离机制

安装配置

Docker 部署

# 基础部署
docker run -p 8080:8080 -p 50051:50051 \
  -e QUERY_DEFAULTS_LIMIT=25 \
  -e AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED=true \
  -e PERSISTENCE_DATA_PATH=/var/lib/weaviate \
  -e DEFAULT_VECTORIZER_MODULE=text2vec-transformers \
  -e ENABLE_MODULES=text2vec-transformers \
  -e TRANSFORMERS_INFERENCE_API=http://t2v:8080 \
  -v weaviate_data:/var/lib/weaviate \
  semitechnologies/weaviate:latest

Docker Compose(推荐)

version: '3.8'
services:
  weaviate:
    image: semitechnologies/weaviate:latest
    ports:
      - "8080:8080"
      - "50051:50051"
    environment:
      QUERY_DEFAULTS_LIMIT: 25
      AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED: 'true'
      PERSISTENCE_DATA_PATH: '/var/lib/weaviate'
      DEFAULT_VECTORIZER_MODULE: 'text2vec-openai'
      ENABLE_MODULES: 'text2vec-openai,generative-openai'
      OPENAI_APIKEY: ${OPENAI_API_KEY}
      CLUSTER_HOSTNAME: 'node1'
    volumes:
      - weaviate_data:/var/lib/weaviate
    restart: unless-stopped

volumes:
  weaviate_data:

Python 客户端

pip install weaviate-client

快速上手

连接和创建 Schema

import weaviate
import weaviate.classes as wvc

# 连接
client = weaviate.connect_to_local()  # localhost:8080

# 创建集合
articles = client.collections.create(
    name="Article",
    vectorizer_config=wvc.config.Configure.Vectorizer.text2vec_openai(),
    generative_config=wvc.config.Configure.Generative.openai(),
    properties=[
        wvc.config.Property(name="title", data_type=wvc.config.DataType.TEXT),
        wvc.config.Property(name="content", data_type=wvc.config.DataType.TEXT),
        wvc.config.Property(name="category", data_type=wvc.config.DataType.TEXT),
        wvc.config.Property(name="year", data_type=wvc.config.DataType.INT),
    ]
)

添加数据

articles = client.collections.get("Article")

# 单条添加
articles.data.insert(
    properties={
        "title": "Python 3.12 新特性",
        "content": "Python 3.12 引入了改进的错误消息...",
        "category": "programming",
        "year": 2024
    }
)

# 批量添加
with articles.batch.dynamic() as batch:
    for item in data_list:
        batch.add_object(properties=item)

搜索

articles = client.collections.get("Article")

# 向量搜索(语义相似度)
result = articles.query.near_text(
    query="Python 编程技巧",
    limit=5
)
for obj in result.objects:
    print(obj.properties["title"])

# 混合搜索(向量 + BM25)
result = articles.query.hybrid(
    query="Python 性能优化",
    alpha=0.5,  # 0=纯BM25, 1=纯向量
    limit=5
)

# BM25 关键词搜索
result = articles.query.bm25(
    query="Python asyncio",
    limit=5
)

# 带过滤的搜索
result = articles.query.near_text(
    query="编程语言",
    limit=5,
    filters=wvc.query.Filter.by_property("year").greater_or_equal(2023)
        & wvc.query.Filter.by_property("category").equal("programming")
)

进阶用法

生成式搜索(RAG)

# 搜索 + 生成
result = articles.generate.near_text(
    query="Python 最佳实践",
    limit=3,
    single_prompt="基于以下内容总结 Python 最佳实践: {content}",
)
for obj in result.objects:
    print(obj.generated)  # LLM 生成的摘要

# 分组生成
result = articles.generate.near_text(
    query="Python 最佳实践",
    limit=5,
    grouped_task="综合以下所有文章,写一份 Python 最佳实践指南"
)
print(result.generated)  # 基于所有结果的综合生成

多租户

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

# 添加租户
multi.tenants.create([
    wvc.tenants.Tenant(name="tenant_a"),
    wvc.tenants.Tenant(name="tenant_b"),
])

# 在特定租户下操作
tenant_a = multi.with_tenant("tenant_a")
tenant_a.data.insert(properties={"content": "租户A的文档"})

# 搜索时自动隔离
results = tenant_a.query.near_text(query="文档", limit=5)

跨引用(关联查询)

# 创建关联
authors = client.collections.create(
    name="Author",
    properties=[
        wvc.config.Property(name="name", data_type=wvc.config.DataType.TEXT),
    ]
)

articles = client.collections.create(
    name="Article",
    properties=[
        wvc.config.Property(name="title", data_type=wvc.config.DataType.TEXT),
    ],
    references=[
        wvc.config.ReferenceProperty(name="author", target_collection="Author")
    ]
)

# 查询时包含引用
result = articles.query.near_text(
    query="Python",
    return_references=wvc.query.QueryReference(
        link_on="author",
        return_properties=["name"]
    )
)

备份与恢复

# 创建备份
result = client.backup.create(
    backup_id="my-backup",
    backend="filesystem",
    include_collections=["Article"]
)

# 恢复
result = client.backup.restore(
    backup_id="my-backup",
    backend="filesystem"
)

常见问题

Q: Weaviate 和 Chroma 怎么选?

  • Chroma:轻量、嵌入式、适合原型和中小规模
  • Weaviate:生产级、混合搜索、多租户、GraphQL,适合大规模部署

Q: 向量化模块选哪个?

  • text2vec-openai:效果好,需要 API Key
  • text2vec-transformers:本地运行,隐私安全
  • text2vec-ollama:对接本地 Ollama
  • text2vec-cohere:多语言效果好

Q: 数据量大时性能下降?

  • 配置 HNSW 参数:efConstructionefmaxConnections
  • 启用产品量化(PQ)减少内存
  • 使用分片实现水平扩展

Q: 如何监控?

Weaviate 暴露 Prometheus 指标在 /v1/meta/metrics,可配合 Grafana 监控。


参考资源

  • GitHub:https://github.com/weaviate/weaviate
  • 文档:https://weaviate.io/developers/weaviate
  • Python 客户端:https://weaviate.io/developers/weaviate/client-libraries/python
  • 教程:https://weaviate.io/developers/academy
  • Slack:https://weaviate.io/slack