跳到主要内容
Open In ColabOpen on GitHub

ElasticsearchEmbeddingsCache

这将帮助您开始使用 Elasticsearch 键值存储。有关所有 ElasticsearchEmbeddingsCache 特性与配置的详细文档,请查阅 API 参考

概述

ElasticsearchEmbeddingsCacheByteStore 的一个实现,它使用您的 Elasticsearch 实例来高效地存储和检索嵌入。

集成详情

类别本地JS 支持包下载量最新包版本
ElasticsearchEmbeddingsCachelangchain_elasticsearchPyPI - DownloadsPyPI - Version

设置

要创建 ElasticsearchEmbeddingsCache 字节存储,您需要一个 Elasticsearch 集群。您可以在本地进行设置创建一个 Elastic 帐户

安装

LangChain 的 ElasticsearchEmbeddingsCache 集成位于 __package_name__ 包中

%pip install -qU langchain_elasticsearch

实例化

现在我们可以实例化我们的字节存储

from langchain_elasticsearch import ElasticsearchEmbeddingsCache

# Example config for a locally running Elasticsearch instance
kv_store = ElasticsearchEmbeddingsCache(
es_url="https://:9200",
index_name="llm-chat-cache",
metadata={"project": "my_chatgpt_project"},
namespace="my_chatgpt_project",
es_user="elastic",
es_password="<GENERATED PASSWORD>",
es_params={
"ca_certs": "~/http_ca.crt",
},
)

使用

您可以使用 mset 方法像这样设置键下的数据

kv_store.mset(
[
["key1", b"value1"],
["key2", b"value2"],
]
)

kv_store.mget(
[
"key1",
"key2",
]
)
[b'value1', b'value2']

您可以使用 mdelete 方法删除数据

kv_store.mdelete(
[
"key1",
"key2",
]
)

kv_store.mget(
[
"key1",
"key2",
]
)
[None, None]

用作嵌入缓存

与其他 ByteStores 类似,您可以将 ElasticsearchEmbeddingsCache 实例用于 文档摄取中的持久缓存,用于 RAG。

然而,缓存的向量默认情况下不可搜索。开发者可以自定义 Elasticsearch 文档的构建,以添加索引向量字段。

这可以通过子类化和覆盖方法来实现

from typing import Any, Dict, List


class SearchableElasticsearchStore(ElasticsearchEmbeddingsCache):
@property
def mapping(self) -> Dict[str, Any]:
mapping = super().mapping
mapping["mappings"]["properties"]["vector"] = {
"type": "dense_vector",
"dims": 1536,
"index": True,
"similarity": "dot_product",
}
return mapping

def build_document(self, llm_input: str, vector: List[float]) -> Dict[str, Any]:
body = super().build_document(llm_input, vector)
body["vector"] = vector
return body

在覆盖映射和文档构建时,请只进行附加修改,保持基本映射不变。

API 参考

有关所有 ElasticsearchEmbeddingsCache 特性与配置的详细文档,请查阅 API 参考: https://python.langchain.ac.cn/api_reference/elasticsearch/cache/langchain_elasticsearch.cache.ElasticsearchEmbeddingsCache.html