跳到主要内容
Weaviate 是一个开源向量数据库,它同时存储对象和向量,可以将向量搜索与结构化过滤相结合。LangChain 通过 weaviate-client 包连接到 Weaviate,weaviate-client 是 Weaviate 的官方 Typescript 客户端。 本指南提供了 Weaviate 向量存储 的快速入门概览。有关所有 WeaviateStore 功能和配置的详细文档,请参阅 API 参考

概览

集成详情

设置

要使用 Weaviate 向量存储,您需要设置一个 Weaviate 实例并安装 @langchain/weaviate 集成包。您还应该安装 weaviate-client 包来初始化客户端以连接到您的实例,如果您想为索引文档分配 ID,请安装 uuid 包。 本指南还将使用 OpenAI 嵌入,这需要您安装 @langchain/openai 集成包。您也可以根据需要使用 其他支持的嵌入模型
npm install @langchain/weaviate @langchain/core weaviate-client uuid @langchain/openai
您需要将 Weaviate 运行在本地或服务器上。有关更多信息,请参阅 Weaviate 文档

凭据

设置实例后,设置以下环境变量
// If running locally, include port e.g. "localhost:8080"
process.env.WEAVIATE_URL = "YOUR_WEAVIATE_URL";
// Optional, for cloud deployments
process.env.WEAVIATE_API_KEY = "YOUR_API_KEY";
如果您在本指南中使用 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"

实例化

连接 Weaviate 客户端

在大多数情况下,您应该使用以下连接辅助函数之一连接到您的 Weaviate 实例
  • connectToWeaviateCloud
  • connectToLocal
  • connectToCustom
import { WeaviateStore } from "@langchain/weaviate";
import { OpenAIEmbeddings } from "@langchain/openai";
import weaviate from "weaviate-client";

const embeddings = new OpenAIEmbeddings({
  model: "text-embedding-3-small",
});

const weaviateClient = weaviate.connectToWeaviateCloud({
   clusterURL: process.env.WEAVIATE_URL!,
  options : {
      authCredentials: new weaviate.ApiKey(process.env.WEAVIATE_API_KEY || ""),
      headers: {
        "X-OpenAI-Api-Key": process.env.OPENAI_API_KEY || "",
        "X-Cohere-Api-Key": process.env.COHERE_API_KEY || "",
      },
    },
});

初始化向量存储

要创建集合,请至少指定集合名称。如果您不指定任何属性,auto-schema 将创建它们。
const vectorStore = new WeaviateStore(embeddings, {
  client: weaviateClient,
  // Must start with a capital letter
  indexName: "Langchainjs_test",
});
要使用 Weaviate 的命名向量、向量化器、重排序器、生成模型等,请在启用向量存储时使用 schema 属性。在创建向量存储时,schema 中的集合名称和其他属性将优先。
const vectorStore = new WeaviateStore(embeddings, {
  client: weaviateClient,
  schema: {
    name: "Langchainjs_test",
    description: "A simple dataset",
    properties: [
      {
        name: "title",
        dataType: dataType.TEXT,
      },
      {
        name: "foo",
        dataType: dataType.TEXT,
      },
    ],
    vectorizers: [
      vectorizer.text2VecOpenAI({
        name: "title",
        sourceProperties: ["title"], // (Optional) Set the source property(ies)
        // vectorIndexConfig: configure.vectorIndex.hnsw()   // (Optional) Set the vector index configuration
      }),
    ],
    generative: weaviate.configure.generative.openAI(),
    reranker: weaviate.configure.reranker.cohere(),
  },
});

管理向量存储

向向量存储添加项目

注意:如果您想将 ID 与索引文档关联,它们必须是 UUID。
import type { Document } from "@langchain/core/documents";
import { v4 as uuidv4 } from "uuid";

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];
const uuids = [uuidv4(), uuidv4(), uuidv4(), uuidv4()];

await vectorStore.addDocuments(documents, { ids: uuids });
[
  '610f9b92-9bee-473f-a4db-8f2ca6e3442d',
  '995160fa-441e-41a0-b476-cf3785518a0d',
  '0cdbe6d4-0df8-4f99-9b67-184009fee9a2',
  '18a8211c-0649-467b-a7c5-50ebb4b9ca9d'
]

从向量存储中删除项目

您可以通过传递 filter 参数按 ID 删除
await vectorStore.delete({ ids: [uuids[3]] });

查询向量存储

创建向量存储并添加相关文档后,您很可能希望在运行链或代理期间查询它。在 Weaviate v3 中,客户端以 collections 作为在数据库中处理对象的主要方式进行交互。collection 对象可以在整个代码库中重复使用

直接查询

执行简单的相似性搜索可以按如下方式完成。Filter 辅助类使得使用带条件的过滤器变得更容易。v3 客户端简化了您使用 Filter 的方式,因此您的代码更简洁。 有关 Weaviate 过滤器语法的更多信息,请参阅 此页面
import { Filters } from "weaviate-client";

const collection = client.collections.use('Langchainjs_test');

const filter = Filters.and(collection.filter.byProperty("source").equal("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"}]
如果您想执行相似性搜索并接收相应的分数,可以运行
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.835] The powerhouse of the cell is the mitochondria [{"source":"https://example.com"}]
* [SIM=0.852] Mitochondria are made out of lipids [{"source":"https://example.com"}]
在 Weaviate 中,混合搜索 通过融合两个结果集,将向量搜索和关键词 (BM25F) 搜索的结果结合起来。要更改关键词和向量组件的相对权重,请在查询中设置 alpha 值。 查看 文档 以获取混合搜索选项的完整列表。
const results = await vectorStore.hybridSearch("biology",
  {
    limit: 1,
    alpha: 0.25,
    targetVector: ["title"],
    rerank: {
      property: "title",
      query: "greeting",
    },
});

检索增强生成 (RAG)

检索增强生成 (RAG) 将信息检索与生成式 AI 模型结合起来。 在 Weaviate 中,RAG 查询包含两部分:搜索查询和模型的提示。Weaviate 首先执行搜索,然后将搜索结果和您的提示都传递给生成式 AI 模型,然后返回生成的响应。
  • @param query 要搜索的查询。
  • @param options 可用于执行混合搜索的选项
  • @param generate 可用于生成的选项。请查看文档以获取完整列表
const results = await vectorStore.generate("hello world",
    {
        singlePrompt: {
            prompt: "Translate this into German: {title}",
        },
        config: generativeParameters.openAI({
            model: "gpt-3.5-turbo",
        }),
    },
    {
        limit: 2,
        targetVector: ["title"],
    }
);

通过转换为检索器进行查询

您还可以将向量存储转换为检索器,以便在您的链中更轻松地使用。
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 参考

有关所有 WeaviateStore 功能和配置的详细文档,请参阅 API 参考
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.