Elasticsearch
仅适用于 Node.js。
Elasticsearch 是一个分布式的、符合 REST 风格的搜索引擎,专为生产级工作负载下的速度和相关性进行了优化。它还支持使用 k-最近邻(kNN)算法的向量搜索,以及 自然语言处理(NLP)的自定义模型。 您可以在此处阅读有关 Elasticsearch 中向量搜索支持的更多信息:链接。
本指南为开始使用 Elasticsearch 向量存储
提供了快速概览。如需查看 ElasticVectorSearch
所有功能和配置的详细文档,请前往 API
参考
页面。
概述
集成详情
| 类 | 包 | Python 支持 | 包的最新版本 |
|---|---|---|---|
ElasticVectorSearch | @langchain/community | ✅ | ![]() |
配置
要使用 Elasticsearch 向量存储,你需要安装 @langchain/community
集成包。
LangChain.js 接受
@elastic/elasticsearch
作为 Elasticsearch 向量存储的客户端。你需要将其作为对等依赖安装。
本指南还将使用 OpenAI
嵌入模型,这要求你安装
@langchain/openai 集成包。你也可以选择使用
其他支持的嵌入模型。
:::提示 请参阅安装集成包的一般说明部分。 :::
- npm
- yarn
- pnpm
npm i @langchain/community @elastic/elasticsearch @langchain/openai @langchain/core
yarn add @langchain/community @elastic/elasticsearch @langchain/openai @langchain/core
pnpm add @langchain/community @elastic/elasticsearch @langchain/openai @langchain/core
凭证
要使用 Elasticsearch 向量存储,你需要运行一个 Elasticsearch 实例。
你可以使用 官方 Docker 镜像 来快速启动,或者使用 Elastic 官方云服务 Elastic Cloud。
连接到 Elastic Cloud 时,你可以阅读 此处 的文档以获取 API 密钥。
如果你在本指南中使用 OpenAI 嵌入模型,还需要设置你的 OpenAI 密钥:
process.env.OPENAI_API_KEY = "YOUR_API_KEY";
如果你想对模型调用进行自动化追踪,也可以通过取消下面的注释来设置你的 LangSmith API 密钥:
// process.env.LANGSMITH_TRACING="true"
// process.env.LANGSMITH_API_KEY="your-api-key"
实例化
实例化 Elasticsearch 将根据您的实例托管位置的不同而有所差异。
import {
ElasticVectorSearch,
type ElasticClientArgs,
} from "@langchain/community/vectorstores/elasticsearch";
import { OpenAIEmbeddings } from "@langchain/openai";
import { Client, type ClientOptions } from "@elastic/elasticsearch";
import * as fs from "node:fs";
const embeddings = new OpenAIEmbeddings({
model: "text-embedding-3-small",
});
const config: ClientOptions = {
node: process.env.ELASTIC_URL ?? "https://127.0.0.1:9200",
};
if (process.env.ELASTIC_API_KEY) {
config.auth = {
apiKey: process.env.ELASTIC_API_KEY,
};
} else if (process.env.ELASTIC_USERNAME && process.env.ELASTIC_PASSWORD) {
config.auth = {
username: process.env.ELASTIC_USERNAME,
password: process.env.ELASTIC_PASSWORD,
};
}
// Local Docker deploys require a TLS certificate
if (process.env.ELASTIC_CERT_PATH) {
config.tls = {
ca: fs.readFileSync(process.env.ELASTIC_CERT_PATH),
rejectUnauthorized: false,
};
}
const clientArgs: ElasticClientArgs = {
client: new Client(config),
indexName: process.env.ELASTIC_INDEX ?? "test_vectorstore",
};
const vectorStore = new ElasticVectorSearch(embeddings, clientArgs);
管理向量存储
向向量存储中添加项目
import type { Document } from "@langchain/core/documents";
const document1: Document = {
pageContent: "The powerhouse of the cell is the mitochondria",
metadata: { source: "https://example.com" },
};
const document2: Document = {
pageContent: "Buildings are made out of brick",
metadata: { source: "https://example.com" },
};
const document3: Document = {
pageContent: "Mitochondria are made out of lipids",
metadata: { source: "https://example.com" },
};
const document4: Document = {
pageContent: "The 2024 Olympics are in Paris",
metadata: { source: "https://example.com" },
};
const documents = [document1, document2, document3, document4];
await vectorStore.addDocuments(documents, { ids: ["1", "2", "3", "4"] });
[ '1', '2', '3', '4' ]
从向量存储中删除项目
您可以通过传入之前使用的相同 ID 来删除存储中的值:
await vectorStore.delete({ ids: ["4"] });
查询向量存储
一旦创建了向量存储并添加了相关文档,您很可能希望在运行链或代理时对其进行查询。
直接查询
执行一个简单的相似性搜索可以按照以下方式完成:
const filter = [
{
operator: "match",
field: "source",
value: "https://example.com",
},
];
const similaritySearchResults = await vectorStore.similaritySearch(
"biology",
2,
filter
);
for (const doc of similaritySearchResults) {
console.log(`* ${doc.pageContent} [${JSON.stringify(doc.metadata, null)}]`);
}
* The powerhouse of the cell is the mitochondria [{"source":"https://example.com"}]
* Mitochondria are made out of lipids [{"source":"https://example.com"}]
向量存储支持Elasticsearch 过滤语法运算符。
如果你想执行相似性搜索并获取相应的分数,可以运行:
const similaritySearchWithScoreResults =
await vectorStore.similaritySearchWithScore("biology", 2, filter);
for (const [doc, score] of similaritySearchWithScoreResults) {
console.log(
`* [SIM=${score.toFixed(3)}] ${doc.pageContent} [${JSON.stringify(
doc.metadata
)}]`
);
}
* [SIM=0.374] The powerhouse of the cell is the mitochondria [{"source":"https://example.com"}]
* [SIM=0.370] Mitochondria are made out of lipids [{"source":"https://example.com"}]
通过转换为检索器进行查询
您还可以将向量存储转换为检索器,以便在您的链中更方便地使用。
const retriever = vectorStore.asRetriever({
// Optional filter
filter: filter,
k: 2,
});
await retriever.invoke("biology");
[
Document {
pageContent: 'The powerhouse of the cell is the mitochondria',
metadata: { source: 'https://example.com' },
id: undefined
},
Document {
pageContent: 'Mitochondria are made out of lipids',
metadata: { source: 'https://example.com' },
id: undefined
}
]
检索增强生成的用法
有关如何将此向量存储用于检索增强生成(RAG)的指南,请参阅以下部分:
API 参考文档
如需详细了解所有 ElasticVectorSearch 的功能和配置,请前往 API
参考文档。
Related
- Vector store conceptual guide
- Vector store how-to guides
