> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-zh.cn/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"}}
# Connect to Pinecone and get an API key.
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 Key。

```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"

# initialize Pinecone client
pc = Pinecone(api_key=api_key)

# create the index
if index_name not in pc.list_indexes().names():
    pc.create_index(
        name=index_name,
        dimension=1536,  # dimensionality of dense model
        metric="dotproduct",  # sparse values supported only for 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

# or from pinecone_text.sparse import SpladeEncoder if you wish to work with SPLADE

# use default tf-idf values
bm25_encoder = BM25Encoder().default()
```

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

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

# fit tf-idf values on your corpus
bm25_encoder.fit(corpus)

# store the values to a json file
bm25_encoder.dump("bm25_values.json")

# load to your BM25Encoder object
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="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/i18n\zh-CN\oss\python\integrations\retrievers\pinecone_hybrid_search.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>

  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>
</div>
