> ## 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.

# Google Memorystore for Redis 集成

> 使用 LangChain 与 Google Memorystore for Redis 向量存储集成。

> [Google Memorystore for Redis](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) 是一款完全托管的服务，由 Redis 内存数据存储提供支持，用于构建应用程序缓存，实现亚毫秒级数据访问。通过 Memorystore for Redis 的 LangChain 集成扩展您的数据库应用程序，以构建 AI 驱动的体验。

本笔记本介绍了如何使用 [Memorystore for Redis](https://cloud.google.com/memorystore/docs/redis/memorystore-for-redis-overview) 存储`MemorystoreVectorStore`类的向量嵌入。

在 [GitHub](https://github.com/googleapis/langchain-google-memorystore-redis-python/) 上了解更多关于该软件包的信息。

[![在 Colab 中打开](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/googleapis/langchain-google-memorystore-redis-python/blob/main/docs/vector_store.ipynb)

## 前置条件

## 开始前

要运行此笔记本，您需要执行以下操作：

* [创建 Google Cloud 项目](https://developers.google.com/workspace/guides/create-project)
* [启用 Memorystore for Redis API](https://console.cloud.google.com/flows/enableapi?apiid=redis.googleapis.com)
* [创建 Memorystore for Redis 实例](https://cloud.google.com/memorystore/docs/redis/create-instance-console)。确保版本大于或等于 7.2。

### 🦜🔗 库安装

集成位于其自己的 `langchain-google-memorystore-redis` 软件包中，因此我们需要安装它。

```python theme={null}
pip install -upgrade --quiet langchain-google-memorystore-redis langchain
```

**Colab 仅限:** 取消注释以下单元格以重启内核，或使用按钮重启内核。对于 Gemini Enterprise Agent Platform Workbench，您可以使用顶部的按钮重启终端。

```python theme={null}
# # Automatically restart kernel after installs so that your environment can access the new packages
# import IPython

# app = IPython.Application.instance()
# app.kernel.do_shutdown(True)
```

### ☁ 设置您的 Google 云项目

设置您的 Google Cloud 项目，以便您可以在本笔记本中利用 Google Cloud 资源。

如果您不知道您的项目 ID，请尝试以下操作：

* 运行 `gcloud config list`。
* 运行 `gcloud projects list`。
* 查看支持页面：[定位项目 ID](https://support.google.com/googleapi/answer/7014113)。

```python theme={null}
# @markdown Please fill in the value below with your Google Cloud project ID and then run the cell.

PROJECT_ID = "my-project-id"  # @param {type:"string"}

# Set the project id
!gcloud config set project {PROJECT_ID}
```

### 🔐 身份验证

以登录此笔记本的 IAM 用户身份验证 Google Cloud，以便访问您的 Google Cloud 项目。

* 如果您使用 Colab 运行此笔记本，请使用以下单元格并继续。
* 如果您使用 Gemini Enterprise Agent Platform Workbench，请查看 [Gemini Enterprise Agent Platform Workbench 设置说明](https://github.com/GoogleCloudPlatform/generative-ai/tree/main/setup-env)。

```python theme={null}
from google.colab import auth

auth.authenticate_user()
```

## 基本用法

### 初始化向量索引

```python theme={null}
import redis
from langchain_google_memorystore_redis import (
    DistanceStrategy,
    HNSWConfig,
    RedisVectorStore,
)

# Connect to a Memorystore for Redis instance
redis_client = redis.from_url("redis://127.0.0.1:6379")

# Configure HNSW index with descriptive parameters
index_config = HNSWConfig(
    name="my_vector_index", distance_strategy=DistanceStrategy.COSINE, vector_size=128
)

# Initialize/create the vector store index
RedisVectorStore.init_index(client=redis_client, index_config=index_config)
```

### 准备文档

在与向量存储交互之前，文本需要处理和数值表示。这包括：

* 加载文本：TextLoader 从文件（例如，“state\_of\_the\_union.txt”）获取文本数据。
* 文本分割：CharacterTextSplitter 将文本分割成更小的块，以便嵌入模型。

> [!WARNING]
>
> `langchain-community`包已不再维护。从`langchain_community`导入的示例可能过时或无法使用。请谨慎使用。

```python theme={null}
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import CharacterTextSplitter

loader = TextLoader("./state_of_the_union.txt")
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
docs = text_splitter.split_documents(documents)
```

### 将文档添加到向量存储

在文本准备和嵌入生成之后，以下方法将它们插入 Redis 向量存储。

#### 方法 1：直接插入的类方法

这种方法将嵌入创建和插入合并为单个步骤，使用 from\_documents 类方法：

> [!WARNING]
>
> `langchain-community`包已不再维护。从`langchain_community`导入的示例可能过时或无法使用。请谨慎使用。

```python theme={null}
from langchain_community.embeddings.fake import FakeEmbeddings

embeddings = FakeEmbeddings(size=128)
redis_client = redis.from_url("redis://127.0.0.1:6379")
rvs = RedisVectorStore.from_documents(
    docs, embedding=embeddings, client=redis_client, index_name="my_vector_index"
)
```

#### 方法 2：基于实例的插入

这种方法在处理新的或现有的 RedisVectorStore 时提供了灵活性：

* \[可选] 创建 RedisVectorStore 实例：实例化 RedisVectorStore 对象以进行自定义。如果您已经有一个实例，请继续下一步。
* 添加带元数据的文本：向实例提供原始文本和元数据。嵌入生成和插入向量存储由系统自动处理。

```python theme={null}
rvs = RedisVectorStore(
    client=redis_client, index_name="my_vector_index", embeddings=embeddings
)
ids = rvs.add_texts(
    texts=[d.page_content for d in docs], metadatas=[d.metadata for d in docs]
)
```

### 执行相似性搜索（KNN）

向量存储填充后，可以搜索与查询在语义上相似的文本。以下是使用默认设置 KNN（K-最近邻）的方法：

* 构建查询：一个自然语言问题表达搜索意图（例如，“总统关于 Ketanji Brown Jackson 说了什么”）。
* 检索相似结果：`similarity_search` 方法找到向量存储中与查询在意义上最接近的项目。

```python theme={null}
import pprint

query = "What did the president say about Ketanji Brown Jackson"
knn_results = rvs.similarity_search(query=query)
pprint.pprint(knn_results)
```

### 执行基于范围的相似性搜索

范围查询通过指定所需的相似度阈值以及查询文本提供更多控制：

* 构建查询：一个自然语言问题定义搜索意图。
* 设置相似度阈值：distance\_threshold 参数确定匹配必须多接近才能被视为相关。
* 检索结果：`similarity_search_with_score` 方法找到向量存储中落在指定相似度阈值范围内的项目。

```python theme={null}
rq_results = rvs.similarity_search_with_score(query=query, distance_threshold=0.8)
pprint.pprint(rq_results)
```

### 执行最大边际相关性（MMR）搜索

MMR 查询旨在找到与查询相关且彼此多样化的结果，减少搜索结果中的冗余。

* 构建查询：一个自然语言问题定义搜索意图。
* 平衡相关性和多样性：lambda\_mult 参数控制严格相关性和促进结果多样性之间的权衡。
* 检索 MMR 结果：`max_marginal_relevance_search` 方法返回基于 lambda 设置优化相关性和多样性组合的项目。

```python theme={null}
mmr_results = rvs.max_marginal_relevance_search(query=query, lambda_mult=0.90)
pprint.pprint(mmr_results)
```

## 将向量存储用作检索器

为了与其他 LangChain 组件无缝集成，可以将向量存储转换为 Retriever。这提供了几个优势：

* LangChain 兼容性：许多 LangChain 工具和方法设计为直接与检索器交互。
* 易用性：`as_retriever()` 方法将向量存储转换为简化查询的格式。

```python theme={null}
retriever = rvs.as_retriever()
results = retriever.invoke(query)
pprint.pprint(results)
```

## 清理

### 从向量存储中删除文档

有时需要从向量存储中删除文档（及其关联的向量）。`delete` 方法提供此功能。

```python theme={null}
rvs.delete(ids)
```

### 删除向量索引

在某些情况下，删除现有的向量索引可能是必要的。常见原因包括：

* 索引配置更改：如果索引参数需要修改，通常需要删除并重新创建索引。
* 存储管理：删除未使用的索引可以帮助释放 Redis 实例中的空间。

注意：向量索引删除是不可逆操作。在继续之前，请确保存储的向量和搜索功能不再需要。

```python theme={null}
# Delete the vector index
RedisVectorStore.drop_index(client=redis_client, index_name="my_vector_index")
```

***

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


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