跳到主要内容
Cloud SQL 是一项完全托管的关系型数据库服务,提供高性能、无缝集成和令人印象深刻的可扩展性。它提供 PostgreSQL、PostgreSQL 和 SQL Server 数据库引擎。利用 Cloud SQL 的 LangChain 集成,扩展您的数据库应用程序以构建 AI 驱动的体验。
本笔记本将介绍如何使用 Cloud SQL for PostgreSQLPostgresVectorStore 类来存储向量嵌入。 GitHub 上了解有关该包的更多信息。 在 Colab 中打开

开始之前

要运行此 notebook,您需要执行以下操作

🦜🔗 库安装

安装集成库 langchain-google-cloud-sql-pg 和嵌入服务库 langchain-google-vertexai
pip install -qU  langchain-google-cloud-sql-pg langchain-google-vertexai
仅限 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)

🔐 身份验证

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

auth.authenticate_user()

☁ 设置您的 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}

基本用法

设置 Cloud SQL 数据库值

Cloud SQL 实例页面中查找您的数据库值。
# @title Set Your Values Here { display-mode: "form" }
REGION = "us-central1"  # @param {type: "string"}
INSTANCE = "my-pg-instance"  # @param {type: "string"}
DATABASE = "my-database"  # @param {type: "string"}
TABLE_NAME = "vector_store"  # @param {type: "string"}

PostgresEngine 连接池

将 Cloud SQL 建立为向量存储库的其中一个要求和参数是一个 PostgresEngine 对象。 PostgresEngine 为您的 Cloud SQL 数据库配置连接池,使您的应用程序能够成功连接并遵循行业最佳实践。 要使用 PostgresEngine.from_instance() 创建 PostgresEngine,您只需提供 4 项内容:
  1. project_id:Cloud SQL 实例所在的 Google Cloud 项目的项目 ID。
  2. region:Cloud SQL 实例所在的区域。
  3. instance:Cloud SQL 实例的名称。
  4. database:要连接到 Cloud SQL 实例上的数据库名称。
默认情况下,将使用 IAM 数据库身份验证作为数据库身份验证方法。此库使用来自环境的 应用默认凭据 (ADC) 所属的 IAM 主体。 有关 IAM 数据库身份验证的更多信息,请参阅: 或者,也可以使用 内置数据库身份验证,使用用户名和密码访问 Cloud SQL 数据库。只需向 PostgresEngine.from_instance() 提供可选的 userpassword 参数
  • user:用于内置数据库身份验证和登录的数据库用户
  • password:用于内置数据库身份验证和登录的数据库密码。
注意:本教程演示了异步接口。所有异步方法都有相应的同步方法。”
from langchain_google_cloud_sql_pg import PostgresEngine

engine = await PostgresEngine.afrom_instance(
    project_id=PROJECT_ID, region=REGION, instance=INSTANCE, database=DATABASE
)

初始化表

PostgresVectorStore 类需要一个数据库表。 PostgresEngine 引擎有一个辅助方法 init_vectorstore_table(),可用于为您创建具有正确架构的表。
from langchain_google_cloud_sql_pg import PostgresEngine

await engine.ainit_vectorstore_table(
    table_name=TABLE_NAME,
    vector_size=768,  # Vector size for VertexAI model(textembedding-gecko@latest)
)

创建嵌入类实例

您可以使用任何 LangChain 嵌入模型。您可能需要启用 Vertex AI API 才能使用 VertexAIEmbeddings。我们建议为生产环境设置嵌入模型的版本,了解更多关于文本嵌入模型的信息。
# enable Vertex AI API
!gcloud services enable aiplatform.googleapis.com
from langchain_google_vertexai import VertexAIEmbeddings

embedding = VertexAIEmbeddings(
    model_name="textembedding-gecko@latest", project=PROJECT_ID
)

初始化默认的 PostgresVectorStore

from langchain_google_cloud_sql_pg import PostgresVectorStore

store = await PostgresVectorStore.create(  # Use .create() to initialize an async vector store
    engine=engine,
    table_name=TABLE_NAME,
    embedding_service=embedding,
)

添加文本

import uuid

all_texts = ["Apples and oranges", "Cars and airplanes", "Pineapple", "Train", "Banana"]
metadatas = [{"len": len(t)} for t in all_texts]
ids = [str(uuid.uuid4()) for _ in all_texts]

await store.aadd_texts(all_texts, metadatas=metadatas, ids=ids)

删除文本

await store.adelete([ids[1]])

搜索文档

query = "I'd like a fruit."
docs = await store.asimilarity_search(query)
print(docs)

按向量搜索文档

query_vector = embedding.embed_query(query)
docs = await store.asimilarity_search_by_vector(query_vector, k=2)
print(docs)

添加索引

通过应用向量索引加速向量搜索查询。了解有关向量索引的更多信息。
from langchain_google_cloud_sql_pg.indexes import IVFFlatIndex

index = IVFFlatIndex()
await store.aapply_vector_index(index)

重新索引

await store.areindex()  # Re-index using default index name

删除索引

await store.aadrop_vector_index()  # Delete index using default name

创建自定义向量存储

向量存储可以利用关系数据来过滤相似性搜索。 创建具有自定义元数据列的表。
from langchain_google_cloud_sql_pg import Column

# Set table name
TABLE_NAME = "vectorstore_custom"

await engine.ainit_vectorstore_table(
    table_name=TABLE_NAME,
    vector_size=768,  # VertexAI model: textembedding-gecko@latest
    metadata_columns=[Column("len", "INTEGER")],
)


# Initialize PostgresVectorStore
custom_store = await PostgresVectorStore.create(
    engine=engine,
    table_name=TABLE_NAME,
    embedding_service=embedding,
    metadata_columns=["len"],
    # Connect to a existing VectorStore by customizing the table schema:
    # id_column="uuid",
    # content_column="documents",
    # embedding_column="vectors",
)

使用元数据过滤器搜索文档

import uuid

# Add texts to the Vector Store
all_texts = ["Apples and oranges", "Cars and airplanes", "Pineapple", "Train", "Banana"]
metadatas = [{"len": len(t)} for t in all_texts]
ids = [str(uuid.uuid4()) for _ in all_texts]
await store.aadd_texts(all_texts, metadatas=metadatas, ids=ids)

# Use filter on search
docs = await custom_store.asimilarity_search_by_vector(query_vector, filter="len >= 6")

print(docs)

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.