Elasticsearch is a distributed, RESTful search and analytics engine, capable of performing both vector and lexical search. It is built on top of the Apache Lucene library.本笔记展示如何使用与
Elasticsearch 向量存储相关的功能。
设置
In order to use theElasticsearch vector search you must install the langchain-elasticsearch package.
凭证
There are two main ways to setup an Elasticsearch instance for use with:- Elastic Cloud: Elastic Cloud is a managed Elasticsearch service. Signup for a free trial.
- Local Install Elasticsearch: Get started with Elasticsearch by running it locally. The easiest way is to use the official Elasticsearch Docker image. See the Elasticsearch Docker documentation for more information.
Running Elasticsearch locally
The easiest way to run Elasticsearch locally for development and testing is using the start-local script. This script sets up Elasticsearch (and optionally Kibana) using Docker with a simple one-line command.elastic-start-local folder containing configuration files and startup scripts. To start Elasticsearch:
http://localhost:9200. The password for the elastic user and API key are automatically generated and stored in the .env file in the elastic-start-local folder.
If you only need Elasticsearch without Kibana, you can use the --esonly option:
The start-local setup is for local testing only and should not be used in production. For production installations, refer to the official Elasticsearch documentation.
Running with authentication
For production, we recommend you run with security enabled. To connect with login credentials, you can use the parameterses_api_key or es_user and es_password.
How to obtain a password for the default “elastic” user?
To obtain your Elastic Cloud password for the default “elastic” user:- Log in to the Elastic Cloud console at cloud.elastic.co
- Go to “Security” > “Users”
- Locate the “elastic” user and click “Edit”
- Click “Reset password”
- Follow the prompts to reset the password
How to obtain an API key?
To obtain an API key:- Log in to the Elastic Cloud console at cloud.elastic.co
- Open Kibana and go to Stack Management > API Keys
- Click “Create API key”
- Enter a name for the API key and click “Create”
- Copy the API key and paste it into the
api_keyparameter
Elastic cloud
To connect to an Elasticsearch instance on Elastic Cloud, you can use either thees_cloud_id parameter or es_url.
初始化
Elasticsearch is running locally on localhost:9200 with docker. For more details on how to connect to Elasticsearch from Elastic Cloud, see connecting with authentication above.管理向量存储
向向量存储添加项目
从向量存储删除项目
查询向量存储
一旦创建了向量存储并添加了相关文档,您很可能希望在链或智能体运行期间对其进行查询。 These examples also show how to use filtering when searching.直接查询
相似度搜索
可以按以下方式执行带元数据过滤的简单相似度搜索:带分数的相似度搜索
如果您想执行相似度搜索并获取对应分数,可以运行:转换为检索器进行查询
您还可以将向量存储转换为检索器,以便在链中更方便地使用。Distance similarity algorithm
Elasticsearch supports the following vector distance similarity algorithms:- cosine
- euclidean
- dot_product
Retrieval strategies
Elasticsearch has big advantages over other vector only databases from its ability to support a wide range of retrieval strategies. In this notebook we will configureElasticsearchStore to support some of the most common retrieval strategies.
By default, ElasticsearchStore uses the DenseVectorStrategy (was called ApproxRetrievalStrategy prior to version 0.2.0).
DenseVectorStrategy
This will return the top k most similar vectors to the query vector. Thek parameter is set when the ElasticsearchStore is initialized. The default value is 10.
Example: Hybrid retrieval with dense vector and keyword search
This example will show how to configure ElasticsearchStore to perform a hybrid retrieval, using a combination of approximate semantic search and keyword based search. We use RRF to balance the two scores from different retrieval methods. To enable hybrid retrieval, we need to sethybrid=True in the DenseVectorStrategy constructor.
Example: Dense vector search with embedding model in Elasticsearch
This example will show how to configureElasticsearchStore to use the embedding model deployed in Elasticsearch for dense vector retrieval.
To use this, specify the model_id in DenseVectorStrategy constructor via the query_model_id argument.
NOTE: This requires the model to be deployed and running in Elasticsearch ML node. See notebook example on how to deploy the model with eland.
SparseVectorStrategy (ELSER)
This strategy uses Elasticsearch’s sparse vector retrieval to retrieve the top-k results. We only support our own “ELSER” embedding model for now. NOTE: This requires the ELSER model to be deployed and running in Elasticsearch ml node. To use this, specifySparseVectorStrategy (was called SparseVectorRetrievalStrategy prior to version 0.2.0) in the ElasticsearchStore constructor. You will need to provide a model ID.
DenseVectorScriptScoreStrategy
This strategy uses Elasticsearch’s script score query to perform exact vector retrieval (also known as brute force) to retrieve the top-k results. (This strategy was calledExactRetrievalStrategy prior to version 0.2.0.)
To use this, specify DenseVectorScriptScoreStrategy in ElasticsearchStore constructor.
BM25Strategy
Finally, you can use full-text keyword search. To use this, specifyBM25Strategy in ElasticsearchStore constructor.
BM25RetrievalStrategy
This strategy allows the user to perform searches using pure BM25 without vector search. To use this, specifyBM25RetrievalStrategy in ElasticsearchStore constructor.
Note that in the example below, the embedding option is not specified, indicating that the search is conducted without using embeddings.
Customise the query
Withcustom_query parameter at search, you are able to adjust the query that is used to retrieve documents from Elasticsearch. This is useful if you want to use a more complex query, to support linear boosting of fields.
Customize the document builder
Withdoc_builder parameter at search, you are able to adjust how a Document is being built using data retrieved from Elasticsearch. This is especially useful if you have indices which were not created using LangChain.
用于检索增强生成
有关如何将此向量存储用于检索增强生成 (RAG) 的指南,请参阅以下部分:FAQ
Question: Im getting timeout errors when indexing documents into Elasticsearch. how do I fix this?
One possible issue is your documents might take longer to index into Elasticsearch. ElasticsearchStore uses the Elasticsearch bulk API which has a few defaults that you can adjust to reduce the chance of timeout errors. This is also a good idea when you’re using SparseVectorRetrievalStrategy. The defaults are:chunk_size: 500max_chunk_bytes: 100MB
chunk_size and max_chunk_bytes parameters to the ElasticsearchStore add_texts method.
Upgrading to ElasticsearchStore
If you’re already using Elasticsearch in your langchain based project, you may be using the old implementations:ElasticVectorSearch and ElasticKNNSearch which are now deprecated. We’ve introduced a new implementation called ElasticsearchStore which is more flexible and easier to use. This notebook will guide you through the process of upgrading to the new implementation.
What’s new?
The new implementation is now one class calledElasticsearchStore which can be used for approximate dense vector, exact dense vector, sparse vector (ELSER), BM25 retrieval and hybrid retrieval, via strategies.
I am using ElasticKNNSearch
Old implementation:I am using ElasticVectorSearch
Old implementation:API 参考
For detailed documentation of allElasticSearchStore features and configurations head to the API reference
连接这些文档到 Claude、VSCode 等工具,通过 MCP 获取实时答案。

