> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# ElasticsearchEmbeddingsCache 集成

> 使用 LangChain Python 与 ElasticsearchEmbeddingsCache 存储集成。

这将帮助您开始使用 Elasticsearch [键值存储](/oss/python/integrations/stores)。有关所有 `ElasticsearchEmbeddingsCache` 功能和配置的详细文档，请访问 [API 参考](https://reference.langchain.com/python/langchain-elasticsearch/cache/ElasticsearchEmbeddingsCache)。

## 概述

`ElasticsearchEmbeddingsCache` 是一个 `ByteStore` 实现，它使用您的 Elasticsearch 实例来高效存储和检索嵌入向量。

### 集成详情

| 类                                                                                                                                   | 包                                                                                           |  本地 | JS 支持 |                                                    下载量                                                   |                                                   版本                                                  |
| :---------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------ | :-: | :---: | :------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------: |
| [`ElasticsearchEmbeddingsCache`](https://reference.langchain.com/python/langchain-elasticsearch/cache/ElasticsearchEmbeddingsCache) | [`langchain-elasticsearch`](https://reference.langchain.com/python/langchain-elasticsearch) |  ✅  |   ❌   | ![PyPI - Downloads](https://img.shields.io/pypi/dm/langchain_elasticsearch?style=flat-square\&label=%20) | ![PyPI - Version](https://img.shields.io/pypi/v/langchain_elasticsearch?style=flat-square\&label=%20) |

## 设置

要创建一个 `ElasticsearchEmbeddingsCache` 字节存储，您需要一个 Elasticsearch 集群。您可以[在本地设置一个](https://www.elastic.co/downloads/elasticsearch)或创建一个 [Elastic 账户](https://www.elastic.co/elasticsearch)。

### 安装

LangChain 的 `ElasticsearchEmbeddingsCache` 集成位于 `langchain-elasticsearch` 包中：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU langchain-elasticsearch
```

## 实例化

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

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_elasticsearch import ElasticsearchEmbeddingsCache

# 本地运行的 Elasticsearch 实例的示例配置
kv_store = ElasticsearchEmbeddingsCache(
    es_url="https://localhost: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` 方法在键下设置数据，如下所示：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
kv_store.mset(
    [
        ["key1", b"value1"],
        ["key2", b"value2"],
    ]
)

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

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[b'value1', b'value2']
```

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

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
kv_store.mdelete(
    [
        "key1",
        "key2",
    ]
)

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

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
[None, None]
```

## 用作嵌入向量缓存

与其他 `ByteStore` 一样，您可以使用 `ElasticsearchEmbeddingsCache` 实例来[在文档摄取中进行持久化缓存](/oss/python/integrations/embeddings#caching)，用于 RAG。

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

这可以通过子类化和重写方法来完成：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
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://reference.langchain.com/python/langchain-elasticsearch/cache/ElasticsearchEmbeddingsCache)

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/stores/elasticsearch.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
