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

# WeaviateStore 集成

> 使用 LangChain JavaScript 集成 WeaviateStore。

[Weaviate](https://weaviate.io/) 是一个开源的向量数据库，它既存储对象也存储向量，允许将向量搜索与结构化过滤相结合。LangChain 通过 weaviate-client 包连接到 Weaviate，这是 Weaviate 的官方 Typescript 客户端。

本指南提供了快速入门 Weaviate [向量存储](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores.md) 的概述。有关所有 `WeaviateStore` 功能和配置的详细文档，请访问 [API 参考](https://reference.langchain.com/javascript/langchain-weaviate/WeaviateStore)。

## 概述

### 集成细节

| 类 | 包 | [PY 支持](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/vectorstores/weaviate.md) | 下载量 | 版本 |
| :- | :- | :-: | :-: | :-: |
| [`WeaviateStore`](https://reference.langchain.com/javascript/langchain-weaviate/WeaviateStore) | [`@langchain/weaviate`](https://www.npmjs.com/package/@langchain/weaviate) | ✅ | ![NPM - 下载量](https://img.shields.io/npm/dm/@langchain/weaviate?style=flat-square\&label=%20&) | ![NPM - 版本](https://img.shields.io/npm/v/@langchain/weaviate?style=flat-square\&label=%20&) |

## 设置

要使用 Weaviate 向量存储，请设置一个 Weaviate 实例并安装 `@langchain/weaviate`、`@langchain/core` 和 `weaviate-client` 以连接到您的部署。

本指南以 [OpenAI 嵌入](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings/openai.md) 为例。您可以使用 [其他支持的嵌入模型](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings.md) 替代。

```bash npm theme={null}
npm install @langchain/weaviate @langchain/core weaviate-client @langchain/openai
```

```bash yarn theme={null}
yarn add @langchain/weaviate @langchain/core weaviate-client @langchain/openai
```

```bash pnpm theme={null}
pnpm add @langchain/weaviate @langchain/core weaviate-client @langchain/openai
```

在本地或服务器上运行 Weaviate。有关更多信息，请参阅 [Weaviate 文档](https://weaviate.io/developers/weaviate/installation)。

### 凭证

设置以下环境变量：

```typescript theme={null}
// 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 密钥：

```typescript theme={null}
process.env.OPENAI_API_KEY = "YOUR_API_KEY";
```

如果您想自动跟踪您的模型调用，也可以通过取消注释以下内容来设置您的 [LangSmith](https://docs.langchain.com/langsmith/observability) API 密钥：

```typescript theme={null}
// process.env.LANGSMITH_TRACING="true"
// process.env.LANGSMITH_API_KEY="your-api-key"
```

## 实例化

### 连接 weaviate 客户端

在大多数情况下，您应该使用连接辅助函数连接到您的 Weaviate 实例：

* connectToWeaviateCloud
* connectToLocal
* connectToCustom

```typescript theme={null}
import { WeaviateStore } from "@langchain/weaviate";
import { OpenAIEmbeddings } from "@langchain/openai";
import weaviate, {
  dataType,
  Filters,
  generativeParameters,
  vectorizer,
} from "weaviate-client";

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

const weaviateClient = await weaviate.connectToWeaviateCloud(
  process.env.WEAVIATE_URL!,
  {
    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` 将创建它们。

```typescript theme={null}
let vectorStore = new WeaviateStore(embeddings, {
  client: weaviateClient,
  indexName: "Langchainjs_test",
});
```

要使用 Weaviate 的命名向量、向量化器、重新排序器、生成模型等，在启用向量存储时使用 `schema` 属性。在创建向量存储时，`schema` 中的集合名称和其他属性将优先。

```typescript theme={null}
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。

```typescript theme={null}
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];
const uuids = [crypto.randomUUID(), crypto.randomUUID(), crypto.randomUUID(), crypto.randomUUID()];

await vectorStore.addDocuments(documents, { ids: uuids });
```

```text theme={null}
[
  '610f9b92-9bee-473f-a4db-8f2ca6e3442d',
  '995160fa-441e-41a0-b476-cf3785518a0d',
  '0cdbe6d4-0df8-4f99-9b67-184009fee9a2',
  '18a8211c-0649-467b-a7c5-50ebb4b9ca9d'
]
```

### 从向量存储删除项目

您可以按 ID 删除，或通过传递 `filter` 参数删除：

```typescript theme={null}
await vectorStore.delete({ ids: [uuids[3]] });
```

## 查询向量存储

一旦您的向量存储创建完成，并且相关文档已添加，您很可能希望在链或智能体运行期间查询它。
在 Weaviate 的 v3 中，客户端通过 `collections` 与数据库中的对象交互作为主要方式。`collection` 对象可以在整个代码库中重复使用

### 直接查询

执行简单的相似度搜索可以按以下方式完成。`Filter` 辅助类使使用带有条件的过滤器变得更加容易。v3 客户端简化了 `Filter` 的使用方式，使您的代码更简洁。

有关 Weaviate 过滤语法的更多信息，请参阅 [此页面](https://weaviate.io/developers/weaviate/api/graphql/filters)。

```typescript theme={null}
const collection = weaviateClient.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)}]`);
}
```

```text theme={null}
* The powerhouse of the cell is the mitochondria [{"source":"https://example.com"}]
* Mitochondria are made out of lipids [{"source":"https://example.com"}]
```

如果您想执行相似度搜索并接收相应的分数，可以运行：

```typescript theme={null}
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)}]`);
}
```

```text theme={null}
* [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 中，`Hybrid search` 通过融合两个结果集来组合向量搜索和关键字（BM25F）搜索的结果。要更改关键字和向量组件的相对权重，请在查询中设置 `alpha` 值。

检查 **[文档](https://weaviate.io/developers/weaviate/search/hybrid)** 获取混合搜索选项的完整列表。

```typescript theme={null}
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 生成选项。检查文档获取完整列表

```typescript theme={null}
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"],
    }
);
```

### 将向量存储转换为检索器

您还可以将向量存储转换为 [检索器](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/retrieval.md)，以便在您的链中更轻松地使用。

```typescript theme={null}
const retriever = vectorStore.asRetriever({
  // Optional filter
  filter: filter,
  k: 2,
});
await retriever.invoke("biology");
```

```javascript theme={null}
[
  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) 的指南，请参阅以下部分：

* [使用 LangChain 构建 RAG 应用](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/rag.md)。
* [智能体 RAG](https://langchain-docs-zh.mintlify.site/langchain/oss/langgraph/agentic-rag.md)
* [检索文档](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/retrieval.md)

***

## API 参考

有关所有 `WeaviateStore` 功能和配置的详细文档，请访问 [API 参考](https://reference.langchain.com/javascript/langchain-weaviate/WeaviateStore)。

***

> 官方原文：[src/oss/javascript/integrations/vectorstores/weaviate.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/javascript/integrations/vectorstores/weaviate.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.