ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

使用 Haystack 集成 Astra DB:AstraDocumentStore 与 AstraEmbeddingRetriever 完全指南

使用 Haystack 集成 Astra DB:AstraDocumentStore 与 AstraEmbeddingRetriever 完全指南 使用 Haystack 集成 Astra DBAstraDocumentStore 与 AstraEmbeddingRetriever 完全指南【免费下载链接】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 2.22 版本官方 API 参考文档为核心系统讲解AstraDocumentStore基于 DataStax Astra DB 的向量文档存储与AstraEmbeddingRetriever向量检索组件的完整 API、配置参数、序列化机制与错误处理并结合仓库内源码与使用指南补充底层原理。读完本文你将能够独立完成 Astra DB 的连接配置、文档写入与批量管理、向量检索管线搭建以及索引策略警告的排查。一、背景为什么在 Haystack 中使用 Astra DBAstra DB 是 DataStax 提供的 serverless 向量数据库构建于 Apache Cassandra 之上原生支持向量搜索与自动扩缩容可部署在 AWS、GCP 或 Azure并支持跨区域部署以获得多区域可用性、低延迟数据访问与数据主权保障详见 AstraDocumentStore 使用指南。在 Haystack 中Astra DB 以官方集成包astra-haystack的形式接入提供两大核心组件haystack_integrations.document_stores.astra.AstraDocumentStore负责与 Astra DB 建立连接、管理 collection、写入/删除/过滤/更新文档。haystack_integrations.components.retrievers.astra.AstraEmbeddingRetriever接收查询向量query embedding从AstraDocumentStore中检索最相关的文档。这套组合常用于 RAG 管线的检索阶段Text Embedder 之后、PromptBuilder 之前、语义搜索管线的末端组件以及抽取式问答管线的检索环节见 AstraEmbeddingRetriever 使用指南。二、安装与连接配置2.1 安装集成包确保已拥有 AstraDB 账户并创建数据库后安装集成pip install astra-haystack如需运行本文的端到端示例还需安装句子向量模型封装用于生成文本与文档向量pip install sentence-transformers-haystack2.2 获取连接凭据AstraDocumentStore通过 Astra DB 的JSON API建立并管理连接。所需的 API endpoint 与应用 token 可在 AstraDB Web UI 中生成点击 Connect 标签页选择JSON API再点击Generate Configuration即可获得。官方强烈建议通过环境变量传递认证信息在运行代码前预先设置export ASTRA_DB_API_ENDPOINThttps://your-database-id-region.apps.astra.datastax.com export ASTRA_DB_APPLICATION_TOKENAstraCS:...这两个环境变量正是AstraDocumentStore.__init__中api_endpoint与token参数的默认值来源见 API 参考文档api_endpoint: Secret Secret.from_env_var(ASTRA_DB_API_ENDPOINT), token: Secret Secret.from_env_var(ASTRA_DB_APPLICATION_TOKEN),当未显式传入时组件会从环境变量读取若两者都缺失初始化会抛出ValueError。三、AstraDocumentStore向量文档存储详解3.1 初始化参数AstraDocumentStore( api_endpoint: Secret Secret.from_env_var(ASTRA_DB_API_ENDPOINT), token: Secret Secret.from_env_var(ASTRA_DB_APPLICATION_TOKEN), collection_name: str documents, embedding_dimension: int 768, duplicates_policy: DuplicatePolicy DuplicatePolicy.NONE, similarity: str cosine, namespace: str | None None, )参数类型默认值说明api_endpointSecret环境变量ASTRA_DB_API_ENDPOINTAstra DB 的 JSON API endpointtokenSecret环境变量ASTRA_DB_APPLICATION_TOKENAstra DB 应用令牌collection_namestrdocuments当前 keyspacenamespace中的 collection 名称可自定义embedding_dimensionint768向量维度必须与写入文档的 embedding 维度一致duplicates_policyDuplicatePolicyDuplicatePolicy.NONE处理重复文档 ID 的策略similaritystrcosine向量相似度度量函数如cosinenamespacestr \| NoneNone数据库中的命名空间在 Cassandra 中称为 keyspace用于组织数据要点embedding_dimension默认为 768与all-mpnet-base-v2等常见模型输出维度一致而使用 384 维模型如all-MiniLM-L6-v2时需显式指定为 384。Collection 的向量维度在创建时固化后续写入的文档向量维度必须匹配否则会报错。3.2 DuplicatePolicy重复文档处理策略DuplicatePolicy定义于 haystack/document_stores/types/policy.py是一个四值枚举class DuplicatePolicy(Enum): NONE none SKIP skip OVERWRITE overwrite FAIL fail四种策略在写入含相同 ID 的文档时的行为DuplicatePolicy.NONE默认策略若同 ID 文档已存在跳过且不写入DuplicatePolicy.SKIP若同 ID 文档已存在跳过且不写入DuplicatePolicy.OVERWRITE若同 ID 文档已存在覆盖写入DuplicatePolicy.FAIL若同 ID 文档已存在抛出DuplicateDocumentError异常。该枚举同时用于AstraDocumentStore.__init__初始化默认策略与write_documents单次写入可覆盖策略。DuplicateDocumentError定义于 haystack/document_stores/errors/errors.py继承自DocumentStoreError。3.3 写入与读取文档写入文档write_documentswrite_documents(documents: list[Document], policy: DuplicatePolicy DuplicatePolicy.NONE) - int接收list[Document]Haystack 文档对象或 dict 列表返回实际写入的文档数量int若policy为FAIL且存在重复 ID抛出DuplicateDocumentError若文档 ID 不是字符串或文档同时包含id与_id字段抛出Exception。统计文档数量count_documentscount_documents() - int返回 document store 中的文档总数。完整的写入-统计循环如下来自 AstraDocumentStore 使用指南from haystack import Document from haystack_integrations.document_stores.astra import AstraDocumentStore document_store AstraDocumentStore() document_store.write_documents( [Document(contentThis is first), Document(contentThis is second)], ) print(document_store.count_documents()) # 2按 ID 读取get_documents_by_id(ids: list[str]) - list[Document]按 ID 列表批量获取文档get_document_by_id(document_id: str) - Document按单个 ID 获取文档未找到时抛出MissingDocumentError同样定义于 haystack/document_stores/errors/errors.py。3.4 过滤与查询过滤文档filter_documentsfilter_documents(filters: dict[str, Any] | None None) - list[Document]返回最多1000条匹配过滤条件的文档。过滤器无效或不受支持时抛出AstraDocumentStoreFilterError继承自FilterError详见第四节错误体系。向量检索searchsearch(query_embedding: list[float], top_k: int, filters: dict[str, Any] | None None) - list[Document]执行向量相似度检索返回与query_embedding最相似的top_k条文档可选filters缩小检索空间。这是AstraEmbeddingRetriever底层调用的核心方法。3.5 删除与更新文档方法签名行为delete_documents(document_ids: list[str]) - None按 ID 列表删除文档若提供了 ID 但没有任何文档被删除抛出MissingDocumentErrordelete_all_documents() - None清空 document store 中所有文档delete_by_filter(filters: dict[str, Any]) - int删除匹配过滤条件的文档返回删除数量过滤器无效时抛出AstraDocumentStoreFilterErrorupdate_by_filter(filters: dict[str, Any], meta: dict[str, Any]) - int将匹配文档的元数据与meta合并更新返回更新数量3.6 元数据字段分析AstraDocumentStore 提供一组面向元数据治理与检索分析的辅助方法count_documents_by_filter(filters) - int统计匹配过滤条件的文档数count_unique_metadata_by_filter(filters, metadata_fields) - dict[str, int]对匹配文档的每个元数据字段统计唯一值数量返回{字段名: 唯一值数量}get_metadata_fields_info() - dict[str, dict[str, str]]返回所有元数据字段及其类型形如{字段名: {type: ...}}get_metadata_field_min_max(metadata_field) - dict[str, Any]返回指定字段的最小值与最大值{min: ..., max: ...}get_metadata_field_unique_values(metadata_field, search_termNone, from_0, size10, filtersNone) - tuple[list[Any], int]检索字段的唯一值列表支持大小写不敏感的子串搜索、分页from_/size与过滤条件返回(分页后的值列表, 总数)。一个值得注意的数据类型陷阱不同原始类型的值即使 Python 比较相等也会被区分对待例如整数1、布尔值True与字符串1会作为三个独立的值返回但存在一个例外——Astra DB 的 Data API 在存储时会把整数值的浮点数如1.0无条件规范化为整数因此写入1.0读取回来会是1int。带小数部分的浮点数如1.5不受影响可正常往返。3.7 连接与序列化index: AstraClient属性返回底层的 AstraClient 索引对象必要时惰性初始化。这是直接操作底层 JSON API 的入口。to_dict() - dict[str, Any]将 document store 序列化为字典用于管线序列化/YAML 持久化。from_dict(data: dict[str, Any]) - AstraDocumentStore从字典反序列化重建 document store。四、错误体系一览haystack_integrations.document_stores.astra.errors模块定义了三级错误类见 API 参考文档错误类基类触发场景AstraDocumentStoreErrorDocumentStoreError所有 AstraDocumentStore 错误的父类AstraDocumentStoreFilterErrorFilterError向 AstraDocumentStore 传入无效过滤器AstraDocumentStoreConfigErrorAstraDocumentStoreError向 AstraDocumentStore 传入无效配置其中DocumentStoreError及其子类DuplicateDocumentError、MissingDocumentError定义于 haystack/document_stores/errors/errors.py。在编写容错逻辑时可统一捕获AstraDocumentStoreError处理配置与过滤类错误单独捕获DuplicateDocumentError处理写入冲突。五、AstraEmbeddingRetriever向量检索组件5.1 初始化参数AstraEmbeddingRetriever( document_store: AstraDocumentStore, filters: dict[str, Any] | None None, top_k: int 10, filter_policy: str | FilterPolicy FilterPolicy.REPLACE, ) - None参数类型默认值说明document_storeAstraDocumentStore必填AstraDocumentStore 实例filtersdict[str, Any] \| NoneNone用于缩小检索空间的过滤器字典top_kint10最大检索文档数filter_policystr \| FilterPolicyFilterPolicy.REPLACE过滤器应用策略过滤器策略filter_policyFilterPolicy枚举定义于 haystack/document_stores/types/filter_policy.py取值含义如下FilterPolicy.REPLACE默认run时传入的运行时过滤器替换初始化时设置的过滤器FilterPolicy.MERGE运行时过滤器与初始化过滤器合并同名字段以运行时值为准合并逻辑会依据过滤器形态比较过滤器 vs 逻辑过滤器调用combine_two_comparison_filters、combine_two_logical_filters等辅助函数见 filter_policy.py逻辑运算符不一致时日志警告并丢弃不匹配的一方。两种策略的实际执行入口为apply_filter_policyfilter_policy.py。5.2 run 与 run_async同步检索runrun(query_embedding: list[float], filters: dict[str, Any] | None None, top_k: int | None None) - dict[str, list[Document]]query_embedding查询向量float 列表通常由 Text Embedder 生成filters运行时过滤器实际应用方式取决于初始化时的filter_policytop_k可选覆盖初始化时的最大检索数量。返回{documents: [Document, ...]}即从AstraDocumentStore检索到的文档列表。异步检索run_async签名与run完全一致将同步检索放入线程池执行避免阻塞事件循环。在async管线如Pipeline.run_async中应使用此方法。5.3 序列化to_dict() - dict[str, Any]序列化组件为字典包含document_store配置与初始化参数from_dict(data: dict[str, Any]) - AstraEmbeddingRetriever从字典重建组件实例。这两个方法让 Retriever 可以无缝嵌入 Haystack 的 YAML 管线序列化机制。5.4 完整使用示例最简单的初始化方式来自 API 参考文档from haystack_integrations.document_stores.astra import AstraDocumentStore from haystack_integrations.components.retrievers.astra import AstraEmbeddingRetriever document_store AstraDocumentStore( api_endpointapi_endpoint, tokentoken, collection_namecollection_name, duplicates_policyDuplicatePolicy.SKIP, embedding_dim384, ) retriever AstraEmbeddingRetriever(document_storedocument_store)六、端到端实战构建语义搜索/RAG 查询管线以下完整示例来自 AstraEmbeddingRetriever 使用指南演示了文档嵌入写入 → 查询管线 → 检索的完整闭环from haystack import Document, Pipeline from haystack.document_stores.types import DuplicatePolicy from haystack_integrations.components.embedders.sentence_transformers import ( SentenceTransformersTextEmbedder, SentenceTransformersDocumentEmbedder, ) from haystack_integrations.components.retrievers.astra import AstraEmbeddingRetriever from haystack_integrations.document_stores.astra import AstraDocumentStore document_store AstraDocumentStore() model sentence-transformers/all-mpnet-base-v2 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., ), ] # 1) 索引管线为文档生成向量并写入 store document_embedder SentenceTransformersDocumentEmbedder(modelmodel) documents_with_embeddings document_embedder.run(documents) document_store.write_documents( documents_with_embeddings.get(documents), policyDuplicatePolicy.SKIP, ) # 2) 查询管线文本向量化 → 向量检索 query_pipeline Pipeline() query_pipeline.add_component( text_embedder, SentenceTransformersTextEmbedder(modelmodel), ) query_pipeline.add_component( retriever, AstraEmbeddingRetriever(document_storedocument_store), ) query_pipeline.connect(text_embedder.embedding, retriever.query_embedding) query How many languages are there? result query_pipeline.run({text_embedder: {text: query}}) print(result[retriever][documents][0])运行结果示例输出为 HaystackDocument对象包含 ID、内容、相似度分数与向量Document(idcfe93bc1c274908801e6670440bf2bbba54fad792770d57421f85ffa2a4fcc94, content: There are over 7,000 languages spoken around the world today., score: 0.8929937, embedding: vector of size 768)实战要点向量一致性索引时 Document Embedder 与查询时 Text Embedder 必须使用同一模型本例均为all-mpnet-base-v2且模型的输出维度必须与AstraDocumentStore(embedding_dimension...)声明的维度一致重复策略write_documents(policyDuplicatePolicy.SKIP)可安全重跑索引脚本已存在的文档 ID 会被跳过而不是覆盖或报错管线连接text_embedder.embedding输出必须显式连接到retriever.query_embedding输入这是向量检索管线的标准接法检索评分返回的score字段即向量相似度默认cosine分数越高代表与查询越相关。七、Indexing Warnings索引策略告警排查当创建AstraDocumentStore时若 collection 已存在且索引配置不匹配可能看到以下两类警告之一Astra DB collection...is detected as having indexing turned on for all fields (either created manually or by older versions of this plugin). This implies stricter limitations on the amount of text each string in a document can store. Consider indexing anew on a fresh collection to be able to store longer texts.或Astra DB collection...is detected as having the following indexing policy:{...}. This does not match the requested indexing policy for this object:{...}. In particular, there may be stricter limitations on the amount of text each string in a document can store. Consider indexing anew on a fresh collection to be able to store longer texts.出现原因collection 已存在且被配置为索引所有字段用于搜索可能因为你在 Haystack 之外创建了该 collection例如在 Astra UI 中创建或通过 AstraPy 的Database.create_collection()该 collection 由旧版本的插件创建。而 Haystack 创建 collection 时会应用一套为你的使用场景优化的索引策略只索引你需要过滤的字段从而允许存储更长的文本并降低写入开销。影响与解决方案影响有限这只是警告应用仍可正常运行除非你尝试存储非常长的文本字段——此时 Astra DB 会返回索引错误推荐方案若可以重新填充数据删除并重建 collection然后重新运行 Haystack 应用使其以优化后的索引策略创建 collection忽略方案若确认不会存储超长文本字段可忽略该警告。八、选型与更多资源在 Haystack 中选择文档存储时可参考 choosing-a-document-store 概念文档 对比不同 store 的适用场景。Astra DB 的定位是serverless、多区域可扩展的托管向量数据库适合需要免运维扩缩容、跨云部署AWS/GCP/Azure或多区域低延迟访问的生产级 RAG 应用。相关代码与文档索引Astra 集成 API 参考当前版本AstraDocumentStore 使用指南AstraEmbeddingRetriever 使用指南DuplicatePolicy 枚举源码FilterPolicy 枚举与过滤器合并逻辑源码DocumentStore 错误类型源码【免费下载链接】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),仅供参考
返回列表