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

# Pinecone 混合搜索集成

> 使用 LangChain Python 集成 Pinecone 混合搜索检索器。

> [Pinecone](https://docs.pinecone.io/docs/overview) 是一个功能广泛的向量数据库。

本笔记本将介绍如何使用一个底层基于 Pinecone 和混合搜索的检索器。

此检索器的逻辑来源于[此文档](https://docs.pinecone.io/docs/hybrid-search)。

要使用 Pinecone，您必须拥有一个 API 密钥和一个环境。
以下是[安装说明](https://docs.pinecone.io/docs/quickstart)。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU  pinecone pinecone-text pinecone-notebooks
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
# 连接到 Pinecone 并获取 API 密钥。
from pinecone_notebooks.colab import Authenticate

Authenticate()

import os

api_key = os.environ["PINECONE_API_KEY"]
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.retrievers import (
    PineconeHybridSearchRetriever,
)
```

我们希望使用 `OpenAIEmbeddings`，因此需要获取 OpenAI API 密钥。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import getpass

if "OPENAI_API_KEY" not in os.environ:
    os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
```

## 设置 Pinecone

您应该只需执行此部分一次。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os

from pinecone import Pinecone, ServerlessSpec

index_name = "langchain-pinecone-hybrid-search"

# 初始化 Pinecone 客户端
pc = Pinecone(api_key=api_key)

# 创建索引
if index_name not in pc.list_indexes().names():
    pc.create_index(
        name=index_name,
        dimension=1536,  # 稠密模型的维度
        metric="dotproduct",  # 仅点积支持稀疏值
        spec=ServerlessSpec(cloud="aws", region="us-east-1"),
    )
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
WhoAmIResponse(username='load', user_label='label', projectname='load-test')
```

现在索引已创建，我们可以使用它了。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
index = pc.Index(index_name)
```

## 获取嵌入和稀疏编码器

嵌入用于稠密向量，分词器用于稀疏向量。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings()
```

要将文本编码为稀疏值，您可以选择 SPLADE 或 BM25。对于领域外任务，我们建议使用 BM25。

有关稀疏编码器的更多信息，您可以查看 pinecone-text 库的[文档](https://pinecone-io.github.io/pinecone-text/pinecone_text.html)。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from pinecone_text.sparse import BM25Encoder

# 或者如果您希望使用 SPLADE，则 from pinecone_text.sparse import SpladeEncoder

# 使用默认的 tf-idf 值
bm25_encoder = BM25Encoder().default()
```

上面的代码使用的是默认的 tf-idf 值。强烈建议将 tf-idf 值拟合到您自己的语料库。您可以按如下方式操作：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
corpus = ["foo", "bar", "world", "hello"]

# 在您的语料库上拟合 tf-idf 值
bm25_encoder.fit(corpus)

# 将值存储到 json 文件
bm25_encoder.dump("bm25_values.json")

# 加载到您的 BM25Encoder 对象
bm25_encoder = BM25Encoder().load("bm25_values.json")
```

## 加载检索器

我们现在可以构建检索器了！

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
retriever = PineconeHybridSearchRetriever(
    embeddings=embeddings, sparse_encoder=bm25_encoder, index=index
)
```

## 添加文本（如果需要）

我们可以选择性地向检索器添加文本（如果它们尚未存在）。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
retriever.add_texts(["foo", "bar", "world", "hello"])
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
100%|██████████| 1/1 [00:02<00:00,  2.27s/it]
```

## 使用检索器

我们现在可以使用检索器了！

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
result = retriever.invoke("foo")
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
result[0]
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Document(page_content='foo', metadata={})
```

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档连接](/use-these-docs)到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/retrievers/pinecone_hybrid_search.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
