跳到主要内容
兼容性:仅适用于 Node.js。
Elasticsearch 是一个分布式、RESTful 搜索引擎,针对生产规模工作负载的速度和相关性进行了优化。它还支持使用 k-最近邻 (kNN) 算法进行向量搜索,以及 用于自然语言处理 (NLP) 的自定义模型。你可以在此处阅读更多关于 Elasticsearch 对向量搜索的支持。 本指南提供了 Elasticsearch 向量存储入门的快速概览。有关所有 ElasticVectorSearch 功能和配置的详细文档,请参阅 API 参考

概览

集成详情

设置

要使用 Elasticsearch 向量存储,你需要安装 @langchain/community 集成包。 LangChain.js 接受 @elastic/elasticsearch 作为 Elasticsearch 向量存储的客户端。你需要将其作为对等依赖项安装。 本指南还将使用 OpenAI 嵌入,这要求你安装 @langchain/openai 集成包。如果你愿意,也可以使用 其他支持的嵌入模型
npm install @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 参考
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.