ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

基于 Elasticsearch 的 LlamaIndex 文档存储(DocStore)实战指南

基于 Elasticsearch 的 LlamaIndex 文档存储(DocStore)实战指南 基于 Elasticsearch 的 LlamaIndex 文档存储DocStore实战指南【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index本指南围绕 LlamaIndex 生态中的ElasticsearchDocumentStore位于 docs/api_reference/api_reference/storage/docstore/elasticsearch.md展开介绍如何用 Elasticsearch 作为文档Document/Node的持久化存储以及如何通过StorageContext将其接入索引构建流程实现跨索引、可恢复的 RAG 数据管线。读完本文你将掌握该存储类的全部构造参数、底层 KV 存储实现机制、默认索引命名规则以及同步/异步 API 的使用方式。一、为什么需要 Elasticsearch 文档存储在 LlamaIndex 中DocumentStore负责保存被切分后的 Node 对象每个 Node 都有唯一 ID是整个索引生命周期中承上启下的一环持久化与复用同一 docstore 可以被多个索引结构复用避免为每个索引重复建库见 keyval_docstore.py 的类文档示例多索引共享SummaryIndex、VectorStoreIndex、SimpleKeywordTableIndex可以共享同一个 docstore生产环境要求默认的SimpleDocumentStore基于内存重启即丢失ElasticsearchDocumentStore则把数据落到 Elasticsearch 索引中适合需要水平扩展、分布式部署的检索场景。ElasticsearchDocumentStore是KVDocumentStore的子类而KVDocumentStore是 LlamaIndex 核心文档存储的通用实现见 keyval_docstore.py。核心测试 test_storage_docstore_elasticsearch.py 验证了这一点ElasticsearchDocumentStore.__mro__中一定包含KVDocumentStore。二、安装与依赖pip install llama-index-storage-docstore-elasticsearch根据 pyproject.toml该包的依赖为依赖版本约束说明llama-index-storage-kvstore-elasticsearch0.4.0,0.5提供ElasticsearchKVStorellama-index-core0.13.0,0.15提供KVDocumentStore基类包本身要求requires-python 3.10,4.0采用MIT许可。虽然依赖是显式声明的但 Elasticsearch 官方客户端elasticsearch属于运行时导入见 kvstore base.py因此实际使用时还需要安装它pip install elasticsearch。三、类签名与参数详解ElasticsearchDocumentStore的构造签名见 base.pydef __init__( self, elasticsearch_kvstore: ElasticsearchKVStore, namespace: Optional[str] None, node_collection_index: str None, ref_doc_collection_index: str None, metadata_collection_index: str None, batch_size: int DEFAULT_BATCH_SIZE, ) - None:各参数含义如下参数默认值说明elasticsearch_kvstore必填一个ElasticsearchKVStore实例负责底层的 ES 读写必须显式传入namespacedocstore命名空间用于区分不同 docstore 的数据避免不同业务互相污染node_collection_indexfllama_index-docstore.data-{namespace}存放 Node 内容与节点元数据含 excluded metadata 和 relationships的 ES 索引ref_doc_collection_indexfllama_index-docstore.ref_doc_info-{namespace}存放ref_doc_id → node_ids映射及文档元数据的 ES 索引metadata_collection_indexfllama_index-docstore.metadata-{namespace}存放 node → ref_doc 引用、doc_hash的 ES 索引batch_sizeDEFAULT_BATCH_SIZE核心库中为1见 types.py批量写入时每批的条目数控制写入吞吐与压力注意namespace与三个 collection index 参数是相互配合的——若显式传入node_collection_index则以传入值为准否则自动生成llama_index-docstore.data-{namespace}。这与KVDocumentStore中namespace suffix的拼接逻辑见 keyval_docstore.py相对应ES 集成把 data/ref_doc_info/metadata 三类集合直接映射成三个独立的 ES 索引。四、第一步构造 ElasticsearchKVStoreElasticsearchDocumentStore要求传入一个ElasticsearchKVStore其构造参数见 kvstore base.py如下ElasticsearchKVStore( index_name: str, # 必填ES 索引名作为 kvstore 的“集合”前缀 es_client: Optional[Any], # 可选已存在的 AsyncElasticsearch 客户端 es_url: Optional[str] None, # 可选ES 连接 URL es_cloud_id: Optional[str] None, # 可选Elastic Cloud ID es_api_key: Optional[str] None, # 可选API Key 认证 es_user: Optional[str] None, # 可选用户名 es_password: Optional[str] None, # 可选密码 )初始化时遵循三条规则见 kvstore base.py传入es_client直接复用该客户端并追加user-agent: llama_index-py-vs请求头传入es_url或es_cloud_id内部通过_get_elasticsearch_client()创建客户端——es_url与cloud_id只能二选一同时传入会抛出ValueError认证方式为es_api_key优先否则用basic_authusername/password两者都未提供抛出ValueError: Either provide a pre-existing AsyncElasticsearch or valid credentials for creating a new connection.此外创建客户端时会立即调用sync_es_client.info()做连通性探测连接失败会记录日志并抛出异常见 kvstore base.py。五、最小可用示例以下示例展示从加载文档到使用 ES 文档存储构建索引的完整链路基于KVDocumentStore类文档中的用法见 keyval_docstore.pyfrom llama_index.core import StorageContext, VectorStoreIndex from llama_index.core.node_parser import SentenceSplitter from llama_index.core.schema import Document from llama_index.storage.docstore.elasticsearch import ElasticsearchDocumentStore from llama_index.storage.kvstore.elasticsearch import ElasticsearchKVStore # 1. 准备数据 documents [Document(textYour long-form document content here...)] nodes SentenceSplitter().get_nodes_from_documents(documents) # 2. 创建 ES KV 存储连接自建 ES kvstore ElasticsearchKVStore( index_namellama_index_docstore, es_urlhttp://localhost:9200, es_userelastic, es_passwordyour-password, ) # 3. 创建 ES 文档存储 docstore ElasticsearchDocumentStore( elasticsearch_kvstorekvstore, namespacedefault, ) # 4. 写入节点 docstore.add_documents(nodes) # 5. 通过 StorageContext 接入索引构建 storage_context StorageContext.from_defaults(docstoredocstore) vector_index VectorStoreIndex(nodes, storage_contextstorage_context) summary_index SummaryIndex(nodes, storage_contextstorage_context)若使用 Elastic Cloud可将es_url换为es_cloud_id需配合es_api_key或账号密码。六、底层存储模型三个 ES 索引KVDocumentStore在写入时会把数据拆分为三类键值对分别落到三个 collection在 ES 集成中即三个索引参见 keyval_docstore.py 与 keyval_docstore.pycollection键值内容datanode collectionnode.node_iddoc_to_json(node)序列化的完整 Node含文本、元数据、relationshipsmetadatanode.node_id{doc_hash: node.hash}若有 ref_doc 则追加{ref_doc_id: ...}ref_doc_infonode.ref_doc_idRefDocInfo.to_dict()即{node_ids: [...], metadata: {...}}写入流程add_documents为_prepare_kv_pairs()先对每个 Node 生成三类 KV 对再通过put_all()按批次写入三个 collection见 keyval_docstore.py。注意多个 Node 指向同一个ref_doc_id时会用_merge_ref_doc_kv_pairs()合并为一条记录见 keyval_docstore.py若allow_updateFalse且 Node 已存在会抛出ValueError: node_id ... already exists. Set allow_update to True to overwrite.见 keyval_docstore.py。在 ES 侧ElasticsearchKVStore.put_all()会把collection与index_name拼成最终索引名并在写入前通过_create_index_if_not_exists()自动建索引mappings 仅启用_source见 kvstore base.py无需手动管理索引。七、常用操作 APIElasticsearchDocumentStore继承自KVDocumentStore直接可用以下方法均见 keyval_docstore.py写入add_documents(docs, allow_updateTrue, batch_sizeNone, store_textTrue)async_add_documents(...)异步版本内部用asyncio.gather并行写三个 collectionL311-L350读取get_document(doc_id, raise_errorTrue)、get_ref_doc_info(ref_doc_id)、get_all_ref_doc_info()、docs属性返回全量Dict[str, BaseNode]查询document_exists(doc_id)、ref_doc_exists(ref_doc_id)、get_document_hash(doc_id)、get_all_document_hashes()删除delete_document(doc_id, raise_errorTrue)、delete_ref_doc(ref_doc_id, raise_errorTrue)级联删除该 ref_doc 下所有 Node见 L557-L575哈希管理set_document_hash(doc_id, doc_hash)、set_document_hashes({doc_id: hash})用于缓存/去重场景以上每个方法都有对应的a前缀异步版本如aget_document、adelete_document便于在 asyncio 应用中保持非阻塞。八、适用场景与限制适合需要把 Node 持久化到 Elasticsearch、与公司现有 ES 基础设施如日志、搜索集群复用的场景多索引共享同一 docstore避免重复入库异步高并发写入场景async_add_documents并行写三个索引。需要注意ElasticsearchDocumentStore只负责文档Node存储不负责向量检索——向量检索应使用llama-index-vector-stores-*系列需要自行保证 Elasticsearch 集群可用性连接失败会在初始化时立刻暴露info()探测若自定义namespace三个 ES 索引名会带上该 namespace 后缀清理数据时需按索引名精确操作batch_size默认值为 1写入大量 Node 时可适当调大以提升吞吐。调试技巧由于索引名遵循llama_index-docstore.data-{namespace}等固定模式可用 Kibana 的 Dev Tools 直接查询例如GET llama_index-docstore.data-default/_search查看已写入的 Node 数据。九、总结ElasticsearchDocumentStore是 LlamaIndex 中把文档存储后置于 Elasticsearch 的官方集成通过组合ElasticsearchKVStore它把 Node 数据、ref_doc 映射和元数据哈希分别落到三个 ES 索引同时完整继承KVDocumentStore的同步/异步读写、删除、哈希管理 API并可借助StorageContext无缝接入索引构建管线。对已使用 Elasticsearch 的团队而言这是将 LlamaIndex 存储层纳入统一基础设施的轻量选择。 /output_article【免费下载链接】llama_indexLlamaIndex is the leading document agent and OCR platform项目地址: https://gitcode.com/GitHub_Trending/ll/llama_index创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表