恒美微站
首页
关于我们
建站服务
主题模板
案例展示
资讯中心
联系我们
Haystack Pinecone 集成:PineconeDocumentStore 与 PineconeEmbeddingRetriever 完整参考
首页
资讯中心
/
Haystack Pinecone 集成:PineconeDocumentStore 与 PineconeEmbeddingRetriever 完整参考
Haystack Pinecone 集成:PineconeDocumentStore 与 PineconeEmbeddingRetriever 完整参考
发布时间:2026/9/13 12:56:57
Haystack Pinecone 集成PineconeDocumentStore 与 PineconeEmbeddingRetriever 完整参考【免费下载链接】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本篇基于 Haystack 官方 API 参考文档version-2.19 版 Pinecone 集成参考系统讲解PineconeDocumentStore文档库与PineconeEmbeddingRetriever检索器的全部初始化参数、方法签名、同步/异步 API 与序列化机制。读完本文你将能够独立完成 Pinecone 向量数据库的接入配置、稠密向量检索管线的搭建并理解过滤器策略filter_policy在检索运行时的底层合并逻辑以及 Pinecone 平台限制对元数据聚合类 API 的具体影响。1. 集成概览与适用场景Pinecone 集成通过独立的pinecone-haystack集成包提供包含两个核心组件PineconeEmbeddingRetriever从PineconeDocumentStore中基于稠密向量dense embeddings检索文档是 RAG 管线中位于文本 Embedder 之后、PromptBuilder 之前的典型组件PineconeDocumentStore基于 Pinecone 向量数据库实现的 Haystack Document Store支持文档的写入、过滤、删除与元数据统计且每个方法均提供同步与异步*_async两套接口。Pinecone 是云托管向量数据库无法在本地机器上自托管这一点与 Qdrant、Weaviate 等可本地运行的方案不同但提供免费的 serverless 额度。集成文档的完整参考路径为 Pinecone API 参考同仓库中还有一份面向用户的教程文档 PineconeDocumentStore 使用指南 与 PineconeEmbeddingRetriever 组件文档。1.1 安装pip install pinecone-haystack1.2 初始化前置条件需要设置环境变量PINECONE_API_KEY推荐或显式传入api_key每个PineconeDocumentStore实例对应 Pinecone 中一个index namespace的组合未指定时两者默认均为default若 index 不存在Document Store 会自动创建它namespace 则在首次写入时自动创建dimension与metric参数只在创建新 index 时生效连接已存在的 index 时会被忽略。2. PineconeEmbeddingRetriever 完整参考2.1 初始化参数__init__( *, document_store: PineconeDocumentStore, filters: dict[str, Any] | None None, top_k: int 10, filter_policy: str | FilterPolicy FilterPolicy.REPLACE ) - None参数类型默认值说明document_storePineconeDocumentStore必填要连接的 Pinecone 文档库实例若传入其他类型会抛出ValueErrorfiltersdict[str, Any] \| NoneNone初始化时固定应用的元数据过滤条件top_kint10单次检索返回的最大文档数filter_policystr \| FilterPolicyFilterPolicy.REPLACE运行时过滤器与初始化过滤器的合并策略注意__init__全部为 keyword-only 参数签名中带有*调用时必须以关键字形式传参。filter_policy 的底层机制FilterPolicy定义在 Haystack 主仓库的 filter_policy.py只有两个枚举值REPLACE默认run时传入的运行时过滤器整体替换初始化时设置的过滤器MERGE运行时过滤器与初始化过滤器按字段合并运行时值覆盖初始值。实际的合并逻辑由同文件中的apply_filter_policy函数L287-L323执行可以细分出四种组合场景比较型过滤器 比较型过滤器、比较型 逻辑型带conditions的 AND/OR、逻辑型 比较型、逻辑型 逻辑型。从源码结构看几个值得注意的细节同名字段冲突处理当 MERGE 策略下运行时比较过滤器与初始过滤器指向同一field时初始过滤器会被忽略并记录警告日志只保留运行时值combine_two_comparison_filtersL275-L284逻辑运算符不匹配若两个逻辑过滤器的顶层operator如一个AND一个OR不一致初始逻辑过滤器会被整体丢弃仅采用运行时过滤器combine_two_logical_filtersL105-L123filter_policy也接受字符串形式replace/merge通过FilterPolicy.from_str转换这保证了 YAML 反序列化时字符串能正确还原为枚举。这些策略函数经由haystack.document_stores.types统一导出可参见 types/init.py。2.2 run / run_asyncrun( query_embedding: list[float], filters: dict[str, Any] | None None, top_k: int | None None, ) - dict[str, list[Document]]query_embedding必填查询文本的稠密向量通常来自上游SentenceTransformersTextEmbedder等文本 Embedder 组件的embedding输出filters运行时过滤器其生效方式取决于初始化时的filter_policy见 2.1 节top_k运行时覆盖初始化top_k的最大返回文档数返回{documents: [Document, ...]}即与query_embedding最相似、按相似度排序的文档列表。run_async签名与run完全一致供异步管线Pipeline.run_async调用避免阻塞事件循环。2.3 序列化与资源管理to_dict() - dict[str, Any] from_dict(data: dict[str, Any]) - PineconeEmbeddingRetriever close() - None close_async() - Noneto_dict/from_dict使该组件可以随Pipeline.to_dict()一起持久化到 JSON/YAML并在反序列化时按类型名自动重建Document Store 本身也在序列化数据中一并保存close/close_async分别释放底层 Document Store 持有的同步与异步客户端资源在应用退出前调用可确保连接干净释放。3. PineconeDocumentStore 完整参考3.1 初始化参数__init__( *, api_key: Secret Secret.from_env_var(PINECONE_API_KEY), index: str default, namespace: str default, batch_size: int 100, dimension: int 768, spec: dict[str, Any] | None None, metric: Literal[cosine, euclidean, dotproduct] cosine, show_progress: bool True ) - None参数类型默认值说明api_keySecret读取环境变量PINECONE_API_KEYPinecone API 密钥以Secret类型承载序列化时不会泄露明文indexstrdefault连接的 Pinecone index不存在时自动创建namespacestrdefaultindex 内的命名空间首次写入时自动创建batch_sizeint100单次 upsert 批次大小。设置时需考虑 Pinecone 官方的配额限制单批次向量数上限dimensionint768向量维度仅在新建 index 时生效specdict[str, Any] \| NoneNone创建 index 的部署规格可选 serverless / pod 模式缺省时使用us-east-1区域的 serverless 默认 spec兼容免费额度metriccosine \| euclidean \| dotproductcosine相似度度量方式仅在新建 index 时生效show_progressboolTrueupsert 文档时是否显示进度条测试或脚本场景建议设为False保持输出干净最小化初始化示例来自教程文档 pinecone-document-store.mdxfrom haystack import Document from haystack_integrations.document_stores.pinecone import PineconeDocumentStore # 确保已设置 PINECONE_API_KEY 环境变量 document_store PineconeDocumentStore( indexdefault, namespacedefault, dimension5, metriccosine, spec{serverless: {region: us-east-1, cloud: aws}}, ) document_store.write_documents( [ Document(contentThis is first, embedding[0.0] * 5), Document(contentThis is second, embedding[0.1, 0.2, 0.3, 0.4, 0.5]), ], ) print(document_store.count_documents())3.2 文档写入write_documentswrite_documents( documents: list[Document], policy: DuplicatePolicy DuplicatePolicy.NONE ) - int将Document列表批量 upsert 到 Pinecone返回实际写入的文档数重要限制PineconeDocumentStore仅支持DuplicatePolicy.OVERWRITE。DuplicatePolicy枚举定义于主仓库 policy.py其通用取值包括OVERWRITE、SKIP、FAIL、NONE但 Pinecone 的实现路径只实现了覆盖语义——重复 ID 的文档会被新数据整体覆盖。索引管线中应统一显式传入policyDuplicatePolicy.OVERWRITE例如document_store.write_documents( documents_with_embeddings.get(documents), policyDuplicatePolicy.OVERWRITE, )write_documents_async为对应的异步版本签名与返回值完全一致。3.3 查询、过滤与删除count_documents() - int count_documents_async() - int filter_documents(filters: dict[str, Any] | None None) - list[Document] filter_documents_async(filters: dict[str, Any] | None None) - list[Document] delete_documents(document_ids: list[str]) - None delete_documents_async(document_ids: list[str]) - None delete_all_documents() - None delete_all_documents_async() - Nonecount_documents返回当前命名空间中的文档总数filter_documents按元数据过滤器返回匹配文档过滤器遵循 Haystack 统一的元数据过滤语法field/operator/value的比较式过滤器以及AND/OR/NOT逻辑组合delete_documents/delete_all_documents按 ID 列表删除或清空命名空间。3.4 条件删除与元数据更新delete_by_filter(filters: dict[str, Any]) - int update_by_filter(filters: dict[str, Any], meta: dict[str, Any]) - int这两个方法有相同的实现前提Pinecone 服务端不支持按过滤条件的批量删除/更新。因此两者的执行策略均为两步走——先按filters检索出命中的文档再在客户端按 ID 删除、或更新meta后重写回 Pineconedelete_by_filter删除所有匹配文档返回删除数量update_by_filter将meta中指定的字段**合并merge**进现有元数据后重写返回更新数量。这意味着大批量删除/更新会产生较多网络往返filters应尽量收敛命中范围。3.5 元数据统计与 Schema 推断受 Pinecone 平台限制以下方法均因 Pinecone 不提供原生聚合 API 而采用拉取文档 Python 侧聚合的实现且统一受TOP_K_LIMIT 1000的上限约束——即一次最多处理 1000 个文档# 按过滤器统计文档数 count_documents_by_filter(filters: dict[str, Any]) - int # 统计匹配文档中若干元数据字段各自的唯一值数量 count_unique_metadata_by_filter( filters: dict[str, Any], metadata_fields: list[str] ) - dict[str, int] # 采样推断元数据字段的类型最多检查 1000 个文档 get_metadata_fields_info() - dict[str, dict[str, str]] # 获取某元数据字段的最小/最大值 get_metadata_field_min_max(metadata_field: str) - dict[str, Any] # 获取某字段的唯一值列表支持搜索词、分页 get_metadata_field_unique_values( metadata_field: str, search_term: str | None None, from_: int 0, size: int 10, filters: dict[str, Any] | None None, ) - tuple[list[Any], int]各方法的返回细节get_metadata_fields_info由于 Pinecone 没有 schema 内省 API该方法通过采样文档元数据推断字段类型类型映射为text文档正文、keyword字符串值、longint 或 float 数值、boolean布尔值。返回形如{ content: {type: text}, category: {type: keyword}, priority: {type: long}, }get_metadata_field_min_max对数值型按数值大小、布尔型返回False/True、字符串型按字母序返回 min/max字段无值空库、字段不存在或类型不支持时两者均为Noneget_metadata_field_unique_valuessearch_term做大小写不敏感的子串匹配from_/size控制分页默认from_0, size10返回(唯一值列表, 匹配总数)。一个值得注意的类型行为是Pinecone 将数值型元数据统一存为float实现中的_convert_meta_to_int会在读取时按字段尝试转回 int因此写入的 int 可能以数值相等的 float 形式返回但类型不同的值仍保持区分——例如 int1与 boolTrue会作为两个独立值返回。上述每个方法均有对应的*_async版本count_documents_by_filter_async、get_metadata_field_unique_values_async等签名与返回值一致。3.6 序列化与资源释放to_dict() - dict[str, Any] from_dict(data: dict[str, Any]) - PineconeDocumentStore close() - None close_async() - Noneto_dict将 index、namespace、spec 等配置序列化为字典api_key以Secret方式安全承载from_dict可从管线快照中还原实例。close/close_async释放同步/异步 Pinecone 客户端资源。4. 端到端实战Embedding 检索查询管线下面给出 API 参考文档中的完整用法示例先完成文档嵌入与写入再组装文本 Embedder → 稠密检索器的查询管线。import os from haystack.document_stores.types import DuplicatePolicy from haystack import Document from haystack import Pipeline # Requires: pip install sentence-transformers-haystack from haystack_integrations.components.embedders.sentence_transformers import SentenceTransformersTextEmbedder from haystack_integrations.components.embedders.sentence_transformers import SentenceTransformersDocumentEmbedder from haystack_integrations.components.retrievers.pinecone import PineconeEmbeddingRetriever from haystack_integrations.document_stores.pinecone import PineconeDocumentStore os.environ[PINECONE_API_KEY] YOUR_PINECONE_API_KEY document_store PineconeDocumentStore(indexmy_index, namespacemy_namespace, dimension768) 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...), Document(contentIn certain places, 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, PineconeEmbeddingRetriever(document_storedocument_store)) query_pipeline.connect(text_embedder.embedding, retriever.query_embedding) query How many languages are there? res query_pipeline.run({text_embedder: {text: query}}) assert res[retriever][documents][0].content There are over 7,000 languages spoken around the world today.要点解析索引侧SentenceTransformersDocumentEmbedder为文档生成 768 维向量write_documents以OVERWRITE策略写入与PineconeDocumentStore唯一支持的去重策略保持一致查询侧text_embedder.embedding输出直接连线到retriever.query_embedding符合 2.2 节所述的 socket 契约结果验证断言确认语义最接近语言数量查询的首条命中为预期文档。若需自定义相似度阈值或字段可在连接时追加top_k、filters输入或利用filter_policyMERGE让运行时过滤器与初始化过滤器叠加生效合并算法见 filter_policy.py。5. 关键限制与适用前提速查仅DuplicatePolicy.OVERWRITE写入不支持SKIP/FAIL语义幂等写入依赖覆盖TOP_K_LIMIT 1000count_documents_by_filter、get_metadata_fields_info、get_metadata_field_min_max、get_metadata_field_unique_values等聚合类 API 的结果以最多 1000 个文档为样本超大库上只能视为近似统计无服务端按条件删改delete_by_filter/update_by_filter均为先查后删/改的客户端实现dimension/metric只在建 index 时生效连接已有 index 时传参无效需提前与已有 index 的规格保持一致云端托管Pinecone 不能本地部署离线环境需改用其他 Document Store 集成异步完备性检索器与文档库的方法均提供_async变体可直接用于Pipeline.run_async场景。综合来看Pinecone 集成覆盖了 Haystack Document Store 协议的读写、过滤、删除、元数据统计全套能力并借助FilterPolicy机制让静态过滤条件与运行时动态过滤灵活组合适合构建托管在云端的 RAG 与语义搜索应用。进一步细节可查阅本仓库中的 Pinecone API 参考原文 与 Document Store 教程。【免费下载链接】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),仅供参考