Haystack × Weaviate 集成实战WeaviateDocumentStore 与 BM25 / Embedding / Hybrid 三种检索器完全指南【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystack本篇技术指南围绕 Haystackversion-2.23与 Weaviate 的官方集成展开系统讲解WeaviateDocumentStore的初始化、认证、文档写入与元数据管理能力以及WeaviateBM25Retriever、WeaviateEmbeddingRetriever、WeaviateHybridRetriever三种检索器的构造参数、run/run_async调用方式与filter_policy的底层合并逻辑。读完本文你将能够基于 Weaviate 独立搭建可运行的关键词检索、向量检索与混合检索链路并将它们嵌入 Haystack Pipeline 构成 RAG 应用。集成概览与接入方式Weaviate 是一个可同时存储向量嵌入与数据对象的多用途向量数据库适合多模态场景。WeaviateDocumentStore可连接任意 Weaviate 实例无论是 Weaviate Cloud Services、Kubernetes 还是本地 Docker 容器。安装方式只有一个命令pip install weaviate-haystack该集成包含四个核心模块均可在haystack_integrations命名空间下找到haystack_integrations.document_stores.weaviate.document_store——WeaviateDocumentStorehaystack_integrations.document_stores.weaviate.auth—— 四类认证凭据类haystack_integrations.components.retrievers.weaviate.bm25_retriever——WeaviateBM25Retrieverhaystack_integrations.components.retrievers.weaviate.embedding_retriever/hybrid_retriever—— 向量与混合检索器更详细的 API 参考见 Weaviate 集成 API 文档对应的用户指南见 weaviatedocumentstore.mdx 与 weaviatebm25retriever.mdx 等页面。方式一Weaviate Embedded临时实例若只想快速试验无需单独部署可直接在客户端内创建嵌入式 Weaviate 集群from haystack_integrations.document_stores.weaviate.document_store import ( WeaviateDocumentStore, ) from weaviate.embedded import EmbeddedOptions document_store WeaviateDocumentStore(embedded_optionsEmbeddedOptions())embedded_options对应 Weaviate 官方客户端中的weaviate.embedded.EmbeddedOptions可用于配置嵌入式实例的完整选项列表。该方式适合开发与测试不适合生产。方式二本地 Docker 容器一份最小可用的docker-compose.yml如下暴露 REST 8080 与 gRPC 50051 端口services: weaviate: command: - --host - 0.0.0.0 - --port - 8080 - --scheme - http image: semitechnologies/weaviate:1.36.2 ports: - 8080:8080 - 50051:50051 volumes: - weaviate_data:/var/lib/weaviate restart: no environment: QUERY_DEFAULTS_LIMIT: 25 AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED: true PERSISTENCE_DATA_PATH: /var/lib/weaviate DEFAULT_VECTORIZER_MODULE: none ENABLE_MODULES: CLUSTER_HOSTNAME: node1 volumes: weaviate_data:启动容器并初始化 Document Storedocker compose up -dfrom haystack_integrations.document_stores.weaviate.document_store import ( WeaviateDocumentStore, ) from haystack import Document document_store WeaviateDocumentStore(urlhttp://localhost:8080) document_store.write_documents( [Document(contentThis is first), Document(contentThis is second)], ) print(document_store.count_documents())注意上述 compose 配置显式开启了无认证访问仅适合本地开发生产环境强烈不建议。认证方案见下文认证体系章节。方式三Weaviate Cloud ServiceWCS先在 Weaviate 云控制台创建集群取得 URL 与 API Key然后import os from haystack_integrations.document_stores.weaviate import ( WeaviateDocumentStore, AuthApiKey, ) os.environ[WEAVIATE_API_KEY] YOUR-API-KEY document_store WeaviateDocumentStore( urlYOUR-WEAVIATE-URL, auth_client_secretAuthApiKey(), )认证体系四类 AuthCredentials 与环境变量haystack_integrations.document_stores.weaviate.auth模块基于AuthCredentialsABC 抽象基类定义了四种认证方式。每个类都将敏感信息存储为 Haystack 的Secret在需要时从环境变量加载并实现resolve_value()将密钥解析为 Weaviate 客户端对应的认证对象WeaviateAuthApiKey、WeaviateAuthBearerToken、WeaviateAuthClientCredentials、WeaviateAuthClientPassword。SupportedAuthTypes枚举通过from_class()将认证类映射为枚举值供序列化使用。认证类默认环境变量适用场景AuthApiKeyWEAVIATE_API_KEYAPI Key 认证WCS 推荐AuthBearerTokenWEAVIATE_ACCESS_TOKEN、WEAVIATE_REFRESH_TOKEN可选已有的 access token 可选 refresh tokenAuthClientCredentialsWEAVIATE_CLIENT_SECRET、WEAVIATE_SCOPE可选OIDC client credential 流程AuthClientPasswordWEAVIATE_USERNAME、WEAVIATE_PASSWORD、WEAVIATE_SCOPE可选OIDC Resource Owner Password 流程其中WEAVIATE_SCOPE可选若设置可为单个字符串如scope1或空格分隔的字符串列表如scope1 scope2。每个认证类都支持to_dict()/from_dict()序列化并可通过from_dict反序列化任意受支持的认证凭据。若想更换环境变量名可显式传入Secretfrom haystack_integrations.document_stores.weaviate.auth import AuthApiKey from haystack.utils.auth import Secret AuthApiKey(api_keySecret.from_env_var(MY_ENV_VAR))WeaviateDocumentStore核心 Document Store 详解构造参数__init__( *, url: str | None None, collection_settings: dict[str, Any] | None None, auth_client_secret: AuthCredentials | None None, additional_headers: dict | None None, embedded_options: EmbeddedOptions | None None, additional_config: AdditionalConfig | None None, grpc_port: int 50051, grpc_secure: bool False ) - None各参数作用urlWeaviate 实例地址。自托管时为http://localhost:8080WCS 时为云集群 URL。collection_settings集合Collection配置。为None时使用名为default的集合属性如下_original_idtext保留原始文档 IDcontenttext文档正文blob_datablob二进制数据blob_mime_typetextMIME 类型scorenumber分数注意默认集合配置刻意省略了 Document 的meta字段因为无法对 meta 结构做假设。官方强烈建议为你的业务场景创建包含正确 meta 属性的自定义集合也可依赖自动 schema 生成但官方不推荐用于生产。auth_client_secret认证凭据取AuthBearerToken、AuthClientPassword、AuthClientCredentials、AuthApiKey之一。additional_headers附加请求头常用于携带模型服务商密钥例如{X-OpenAI-Api-Key: THE-KEY}或{X-HuggingFace-Api-Key: THE-KEY}当 Weaviate 侧配置了向量化模块时使用。embedded_options设置后在客户端内部创建嵌入式 Weaviate 集群。additional_config传给 Weaviate 的额外高级配置。grpc_portgRPC 连接端口默认 50051。grpc_secure是否对底层 gRPC API 使用安全通道默认False。惰性客户端与集合访问WeaviateDocumentStore提供四个惰性属性首次访问时才创建并连接client同步 Weaviate 客户端async_client异步客户端collection同步集合对象Collection[dict[str, Any], None]async_collection异步集合对象配套的close()/close_async()分别释放同步与异步资源三个检索器与 Document Store 也各自实现了close/close_async用于释放底层 Document Store 资源。文档写入write_documents 与 DuplicatePolicywrite_documents( documents: list[Document], policy: DuplicatePolicy DuplicatePolicy.NONE ) - intDuplicatePolicy定义在 haystack/document_stores/types/policy.py取值包括NONE默认不检查重复、SKIP跳过重复、OVERWRITE覆盖、FAIL报错。一个值得注意的实现细节官方推荐使用OVERWRITE策略因为它是唯一可以使用 Weaviate batch API 的策略写入速度更快其余策略无法使用 batch API——batch 接口不返回文档是否已存在的信息这会导致FAIL策略无法返回错误、SKIP策略无法跳过重复文档。异常情况输入无效时抛ValueError使用FAIL策略发现重复文档时抛DuplicateDocumentError批量写入失败时抛DocumentStoreError。异步版本为write_documents_async。文档检索filter_documents 与元数据过滤filter_documents(filters: dict[str, Any] | None None) - list[Document]按 Haystack 的DocumentStore.filter_documents()协议执行过滤。一个易踩的坑contains过滤操作符是大小写敏感的子串匹配。如需大小写不敏感匹配请在构造 filter 前先对值做归一化处理。文档管理计数、删除、更新count_documents()/count_documents_async()返回存储中的文档总数。count_documents_by_filter(filters)/ 异步版按过滤器统计文档数量。delete_documents(document_ids)/ 异步版按文档 ID 列表删除。delete_by_filter(filters)/ 异步版删除所有匹配过滤器的文档返回删除数量。update_by_filter(filters, meta)/ 异步版更新所有匹配文档的元数据meta会与现有元数据合并返回更新数量。delete_all_documents(*, recreate_indexFalse, batch_size1000)/ 异步版recreate_indexFalse保留集合按批次迭代删除batch_size默认 1000需小于等于 Weaviate 部署的QUERY_MAXIMUM_RESULTS配置默认 10000recreate_indexTrue直接 drop 集合再重建官方推荐用于性能优化。元数据统计能力WeaviateDocumentStore实现了丰富的元数据统计方法为检索结果可视化、faceting 类功能提供数据支撑get_metadata_fields_info()/ 异步版返回元数据字段名与类型映射排除特殊字段content、blob_data、blob_mime_type、_original_id、score。示例返回{number: {type: int}, date: {type: date}, category: {type: text}}。get_metadata_field_min_max(metadata_field)/ 异步版返回数值或日期字段的最小/最大值字段名可加meta.前缀如meta.year或year字段不存在或不支持 min/max 时抛ValueError。count_unique_metadata_by_filter(filters, metadata_fields)/ 异步版对指定字段统计去重值数量字段不存在时抛ValueError。get_metadata_field_unique_values(metadata_field, search_termNone, from_0, size10, filtersNone)/ 异步版分页返回字段去重值search_term做大小写不敏感的子串过滤无词干还原返回(去重值列表, 去重总数)。一个由 weaviate-client 协议决定的类型陷阱值得注意标量int元数据值取回时会变成float。原因是 weaviate-client 没有标量 int 的线上协议字段——非列表属性被打包进google.protobuf.Struct其Value类型只有number_valuedoubleint/float 的区分在到达 Weaviate 之前就丢失了GroupByAggregate对数值分组键的解码方式相同因此即使 schema 显式声明DataType.INT也如此。而列表型 int 字段如meta{tags: [1, 2]}不受影响它们走专用的IntArrayProperties线上类型。序列化与资源管理to_dict()/from_dict()对所有组件通用to_dict返回可序列化字典from_dict从字典反序列化。配合 Haystack 的Pipeline.dumps()/Pipeline.loads()整个 Weaviate 检索链路含认证凭据、过滤器配置都可以 YAML/JSON 形式持久化并在反序列化时完整还原。WeaviateBM25Retriever关键词检索__init__( *, document_store: WeaviateDocumentStore, filters: dict[str, Any] | None None, top_k: int 10, filter_policy: str | FilterPolicy FilterPolicy.REPLACE ) - None基于 BM25 算法的关键词检索组件。基本用法from haystack_integrations.document_stores.weaviate.document_store import ( WeaviateDocumentStore, ) from haystack_integrations.components.retrievers.weaviate.bm25_retriever import ( WeaviateBM25Retriever, ) document_store WeaviateDocumentStore(urlhttp://localhost:8080) retriever WeaviateBM25Retriever(document_storedocument_store) retriever.run(queryHow to make a pizza, top_k3)document_store必需的WeaviateDocumentStore实例。filters初始化时设定的自定义过滤器。top_k最多返回的文档数默认 10。filter_policy过滤器应用策略默认FilterPolicy.REPLACE。run(query, filtersNone, top_kNone)返回{documents: [...]}run_async为异步版本。运行时传入的filters如何生效取决于初始化时选定的filter_policy。WeaviateEmbeddingRetriever向量检索__init__( *, document_store: WeaviateDocumentStore, filters: dict[str, Any] | None None, top_k: int 10, distance: float | None None, certainty: float | None None, filter_policy: str | FilterPolicy FilterPolicy.REPLACE ) - None基于查询向量与文档向量相似度检索的组件。distance文档嵌入与查询向量之间允许的最大距离阈值。certainty结果项与搜索向量之间的归一化距离即确定性分数。重要约束distance与certainty不能同时提供否则抛ValueError。二者都作用于 Weaviate 的向量相似度阈值语义互斥请按部署与业务需求二选一。run(query_embedding: list[float], filtersNone, top_kNone, distanceNone, certaintyNone)返回{documents: [...]}同样提供run_async。注意它的输入是query_embedding查询向量而非查询文本因此在使用前需要先用 Text Embedder 之类的组件将查询文本转换为向量。WeaviateHybridRetriever混合检索与 alpha 调参__init__( *, document_store: WeaviateDocumentStore, filters: dict[str, Any] | None None, top_k: int 10, alpha: float 0.7, max_vector_distance: float | None None, filter_policy: str | FilterPolicy FilterPolicy.REPLACE ) - NoneWeaviateHybridRetriever将 BM25 关键词检索与向量相似度检索并行执行并在 Weaviate 服务端融合为一个排序结果是兼顾关键词召回与语义召回的默认选择。alpha混合权重因子取值范围[0.0, 1.0]控制两种打分对最终结果的贡献alpha 0.0仅使用关键词BM25打分alpha 1.0仅使用向量相似度打分中间值按比例混合值越大越偏向向量分值越小越偏向 BM25 分。默认alpha 0.7这也是 Weaviate 服务端的默认值。max_vector_distance可选阈值在混合前将向量部分限制在最大向量距离内——距离超过该阈值的候选会从向量部分剔除。适合在保留关键词召回的同时剪除低质量向量匹配设为None则使用 Weaviate 默认行为不设显式截断。run与run_async签名一致同时需要query文本与query_embedding向量并支持运行时覆盖top_k、alpha、max_vector_distance、filtersrun( query: str, query_embedding: list[float], filters: dict[str, Any] | None None, top_k: int | None None, alpha: float | None None, max_vector_distance: float | None None, ) - dict[str, list[Document]]独立使用示例from haystack_integrations.document_stores.weaviate.document_store import ( WeaviateDocumentStore, ) from haystack_integrations.components.retrievers.weaviate import WeaviateHybridRetriever document_store WeaviateDocumentStore(urlhttp://localhost:8080) retriever WeaviateHybridRetriever(document_storedocument_store) # using a fake vector to keep the example simple retriever.run(queryHow many languages are there?, query_embedding[0.1] * 768)filter_policyREPLACE 与 MERGE 的底层实现filter_policy是三个检索器共有的参数。FilterPolicy枚举定义在 haystack/document_stores/types/filter_policy.pyREPLACE默认运行时过滤器直接替换初始化时设定的过滤器便于针对不同查询动态调整过滤条件。MERGE运行时过滤器与初始化过滤器合并进一步收窄搜索范围键冲突时运行时值覆盖初始化值。其底层实现为同文件中的apply_filter_policy(filter_policy, init_filters, runtime_filters, default_logical_operatorAND)。源码逻辑filter_policy.py表明仅当策略为MERGE且运行时与初始化过滤器均非空时才会执行合并合并过程按过滤器形态比较型ComparisonFilter与逻辑型LogicalFilter的四种组合分别调用对应的组合函数将两个过滤器以默认AND逻辑操作符合并成一个新的过滤器树其余情况直接返回runtime_filters or init_filters。在 Pipeline 中的实战混合检索 RAG将WeaviateHybridRetriever嵌入 Haystack Pipeline 的典型做法是文本经 Document Embedder 向量化后写入 Weaviate查询侧用 Text Embedder 生成查询向量两者在 Pipeline 中按组件连接。完整示例需要sentence-transformers-haystack包pip install sentence-transformers-haystackfrom haystack import Document, Pipeline from haystack.document_stores.types import DuplicatePolicy from haystack_integrations.components.embedders.sentence_transformers import ( SentenceTransformersTextEmbedder, SentenceTransformersDocumentEmbedder, ) from haystack_integrations.document_stores.weaviate.document_store import ( WeaviateDocumentStore, ) from haystack_integrations.components.retrievers.weaviate import ( WeaviateHybridRetriever, ) document_store WeaviateDocumentStore(urlhttp://localhost:8080) documents [ Document(contentThere are over 7,000 languages spoken around the world today.), Document( contentElephants have been observed to behave in a way that indicates a high level of self-awareness, such as recognizing themselves in mirrors. ), Document( contentIn certain parts of the world, like the Maldives, Puerto Rico, and San Diego, you can witness the phenomenon of bioluminescent waves. ), ] document_embedder SentenceTransformersDocumentEmbedder() documents_with_embeddings document_embedder.run(documents) document_store.write_documents( documents_with_embeddings.get(documents), policyDuplicatePolicy.OVERWRITE, ) query_pipeline Pipeline() query_pipeline.add_component(text_embedder, SentenceTransformersTextEmbedder()) query_pipeline.add_component(retriever, WeaviateHybridRetriever(document_storedocument_store)) query_pipeline.connect(text_embedder.embedding, retriever.query_embedding) result query_pipeline.run( { text_embedder: {text: How many languages are there?}, retriever: {query: How many languages are there?}, } ) print(result[retriever][documents])值得注意的是WeaviateHybridRetriever在 Pipeline 中最常见的位置是①RAG 管道中位于 Text Embedder 之后、PromptBuilder之前②混合检索管道的末位组件③抽取式问答管道中位于 Text Embedder 之后、Extractive Reader 之前。核心运行变量是query字符串与query_embedding浮点列表输出变量为documents列表。实战注意事项与最佳实践集合 schema 先行默认default集合不含meta属性生产环境务必为你的元数据结构创建自定义collection_settings避免过滤/统计能力受限。写文档用OVERWRITE这是唯一走 batch API 的策略吞吐性能最优需要严格去重语义时再考虑FAIL/SKIP代价是失去 batch 加速。distance与certainty二选一同时传入会抛ValueError两者分别对应 Weaviate 向量搜索的两种阈值语义。混合检索调alpha是核心杠杆偏关键词召回调低、偏语义召回调高max_vector_distance可在保留关键词召回的同时剪除低质量向量候选。contains过滤大小写敏感需要不敏感匹配时先归一化再构造过滤器。int 元数据会变 float标量 int 元数据经 Weaviate 取回时变为 float 是 weaviate-client 协议所致业务侧做类型断言时需兼容。清理索引用recreate_indexTrue清空集合时 drop-and-recreate 比逐批删除更快是官方推荐路径。资源释放Pipeline 运行完毕或应用退出前调用 Document Store 与检索器的close()同步场景或close_async()异步场景释放底层连接资源。认证凭据走环境变量四种AuthCredentials默认从WEAVIATE_*环境变量读取密钥序列化时不落盘敏感信息需要自定义变量名时显式传入Secret.from_env_var(...)。异步能力贯穿始终Document Store 与三个检索器均提供*_async方法族配合 Haystack 的异步 Pipeline 可在高并发场景获得更好的吞吐。【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystack创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考