Skip to main content
Google Memorystore for Redis 是一种完全托管的服务,由 Redis 内存数据存储提供支持,用于构建提供亚毫秒级数据访问的应用缓存。利用 Memorystore for Redis 的 LangChain 集成,扩展您的数据库应用,构建 AI 驱动的体验。
本 notebook 介绍如何使用 Memorystore for Redis 通过 MemorystoreDocumentLoaderMemorystoreDocumentSaver保存、加载和删除 LangChain 文档 GitHub 上了解更多关于该软件包的信息。 Open In Colab

开始之前

要运行本 notebook,您需要完成以下步骤: 在本 notebook 的运行环境中确认可以访问数据库后,填写以下值并在运行示例脚本前先运行该单元格。
# @markdown Please specify an endpoint associated with the instance and a key prefix for demo purpose.
ENDPOINT = "redis://127.0.0.1:6379"  # @param {type:"string"}
KEY_PREFIX = "doc:"  # @param {type:"string"}

🦜🔗 安装库

该集成位于独立的 langchain-google-memorystore-redis 包中,需要单独安装。
pip install -upgrade --quiet langchain-google-memorystore-redis
仅限 Colab:取消注释以下单元格以重启内核,或使用按钮重启内核。对于 Vertex AI Workbench,可以使用顶部的按钮重启终端。
# # 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 Cloud 项目

设置您的 Google Cloud 项目,以便在本 notebook 中使用 Google Cloud 资源。 如果您不知道项目 ID,请尝试以下方法:
  • 运行 gcloud config list
  • 运行 gcloud projects list
  • 查看支持页面:查找项目 ID
# @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}

🔐 身份验证

以登录本 notebook 的 IAM 用户身份对 Google Cloud 进行身份验证,以访问您的 Google Cloud 项目。
  • 如果您使用 Colab 运行本 notebook,请使用下面的单元格并继续。
  • 如果您使用 Vertex AI Workbench,请查看此处的设置说明。
from google.colab import auth

auth.authenticate_user()

基本用法

保存文档

使用 MemorystoreDocumentSaver.add_documents(<documents>) 保存 LangChain 文档。要初始化 MemorystoreDocumentSaver 类,您需要提供以下两项:
  1. client - 一个 redis.Redis 客户端对象。
  2. key_prefix - 用于在 Redis 中存储文档的键前缀。
文档将以指定的 key_prefix 前缀和随机生成的键进行存储。您也可以通过在 add_documents 方法中指定 ids 来自定义键的后缀。
import redis
from langchain_core.documents import Document
from langchain_google_memorystore_redis import MemorystoreDocumentSaver

test_docs = [
    Document(
        page_content="Apple Granny Smith 150 0.99 1",
        metadata={"fruit_id": 1},
    ),
    Document(
        page_content="Banana Cavendish 200 0.59 0",
        metadata={"fruit_id": 2},
    ),
    Document(
        page_content="Orange Navel 80 1.29 1",
        metadata={"fruit_id": 3},
    ),
]
doc_ids = [f"{i}" for i in range(len(test_docs))]

redis_client = redis.from_url(ENDPOINT)
saver = MemorystoreDocumentSaver(
    client=redis_client,
    key_prefix=KEY_PREFIX,
    content_field="page_content",
)
saver.add_documents(test_docs, ids=doc_ids)

加载文档

初始化一个加载器,加载存储在 Memorystore for Redis 实例中具有特定前缀的所有文档。 使用 MemorystoreDocumentLoader.load()MemorystoreDocumentLoader.lazy_load() 加载 LangChain 文档。lazy_load 返回一个生成器,仅在迭代时查询数据库。要初始化 MemorystoreDocumentLoader 类,您需要提供:
  1. client - 一个 redis.Redis 客户端对象。
  2. key_prefix - 用于在 Redis 中存储文档的键前缀。
import redis
from langchain_google_memorystore_redis import MemorystoreDocumentLoader

redis_client = redis.from_url(ENDPOINT)
loader = MemorystoreDocumentLoader(
    client=redis_client,
    key_prefix=KEY_PREFIX,
    content_fields=set(["page_content"]),
)
for doc in loader.lazy_load():
    print("Loaded documents:", doc)

删除文档

使用 MemorystoreDocumentSaver.delete() 删除 Memorystore for Redis 实例中所有具有指定前缀的键。如果知道键的后缀,也可以指定。
docs = loader.load()
print("Documents before delete:", docs)

saver.delete(ids=[0])
print("Documents after delete:", loader.load())

saver.delete()
print("Documents after delete all:", loader.load())

高级用法

自定义文档页面内容和元数据

当初始化加载器时指定了多个内容字段,加载的文档的 page_content 将包含一个 JSON 编码的字符串,其顶层字段等于 content_fields 中指定的字段。 如果指定了 metadata_fields,加载的文档的 metadata 字段将只包含等于指定 metadata_fields 的顶层字段。如果元数据字段的任何值以 JSON 编码字符串存储,则在加载到元数据字段之前会先进行解码。
loader = MemorystoreDocumentLoader(
    client=redis_client,
    key_prefix=KEY_PREFIX,
    content_fields=set(["content_field_1", "content_field_2"]),
    metadata_fields=set(["title", "author"]),
)