Skip to main content
Open In ColabOpen on GitHub

Google Spanner

Spanner 是一种高度可扩展的数据库,结合了无限的可扩展性与关系型语义,如二级索引、强一致性、模式和 SQL,在一个简单的解决方案中提供了 99.999% 的可用性。

本笔记本介绍了如何使用Spanner进行向量搜索以及SpannerVectorStore类。

Learn more about the package on GitHub.

Open In Colab

开始之前

要运行此笔记本,您需要执行以下操作:

🦜🔗 库安装

The integration lives in its own langchain-google-spanner package, so we need to install it.

%pip install --upgrade --quiet langchain-google-spanner langchain-google-vertexai
Note: you may need to restart the kernel to use updated packages.

仅限 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)

🔐 认证

请以笔记本中已登录的IAM用户身份向Google Cloud进行认证,以便访问您的Google Cloud项目。

  • 如果您在Colab中运行此笔记本,请使用下方单元格继续。
  • 如果您正在使用Vertex AI工作区,请参阅设置说明这里
from google.colab import auth

auth.authenticate_user()

☁ 设置您的Google云项目

设置您的Google Cloud项目,以便在此笔记本中利用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}
%env GOOGLE_CLOUD_PROJECT={PROJECT_ID}

💡 API 启用

langchain-google-spanner包需要您在Google Cloud项目中启用Spanner API

# enable Spanner API
!gcloud services enable spanner.googleapis.com

基本用法

设置Spanner数据库值

Spanner实例页面中查找您的数据库值。

# @title Set Your Values Here { display-mode: "form" }
INSTANCE = "my-instance" # @param {type: "string"}
DATABASE = "my-database" # @param {type: "string"}
TABLE_NAME = "vectors_search_data" # @param {type: "string"}

初始化表格

The SpannerVectorStore 类实例需要一个带有 id、content 和 embeddings 列的数据库表。

可用于为您创建正确架构表的辅助方法init_vector_store_table()

from langchain_google_spanner import SecondaryIndex, SpannerVectorStore, TableColumn

SpannerVectorStore.init_vector_store_table(
instance_id=INSTANCE,
database_id=DATABASE,
table_name=TABLE_NAME,
# Customize the table creation
# id_column="row_id",
# content_column="content_column",
# metadata_columns=[
# TableColumn(name="metadata", type="JSON", is_null=True),
# TableColumn(name="title", type="STRING(MAX)", is_null=False),
# ],
# secondary_indexes=[
# SecondaryIndex(index_name="row_id_and_title", columns=["row_id", "title"])
# ],
)

创建一个嵌入类实例

您可以用任何 LangChain嵌入模型。 可能需要启用 Vertex AI API 才能使用 VertexAIEmbeddings。我们建议为生产设置嵌入模型的版本,了解更多关于文本嵌入模型的信息。

# enable Vertex AI API
!gcloud services enable aiplatform.googleapis.com
from langchain_google_vertexai import VertexAIEmbeddings

embeddings = VertexAIEmbeddings(
model_name="textembedding-gecko@latest", project=PROJECT_ID
)
API 参考:VertexAI 嵌入

SpannerVectorStore

要初始化 SpannerVectorStore 类,您需要提供4个必需参数和其他可选参数,只有在与默认值不同时才需要传递

  1. instance_id - Cloud Spanner 实例的名称
  2. database_id - Spanner数据库的名称
  3. table_name - 数据库中用于存储文档及其嵌入的表名。
  4. embedding_service - 用于生成嵌入的Embeddings实现。
db = SpannerVectorStore(
instance_id=INSTANCE,
database_id=DATABASE,
table_name=TABLE_NAME,
embedding_service=embeddings,
# Connect to a custom vector store table
# id_column="row_id",
# content_column="content",
# metadata_columns=["metadata", "title"],
)

添加文档

在向量存储中添加文档。

import uuid

from langchain_community.document_loaders import HNLoader

loader = HNLoader("https://news.ycombinator.com/item?id=34817881")

documents = loader.load()
ids = [str(uuid.uuid4()) for _ in range(len(documents))]
db.add_documents(documents, ids)
API 参考:HNLoader

搜索文档

在向量存储中通过相似性搜索来查找文档。

db.similarity_search(query="Explain me vector store?", k=3)

搜索文档

在向量存储中使用最大边际相关性搜索来检索文档。

db.max_marginal_relevance_search("Testing the langchain integration with spanner", k=3)

删除文档

要从向量存储中删除文档,请使用在初始化 VectorStore 时对应于 `row_id` 列值的 ID。

db.delete(ids=["id1", "id2"])

删除文档

要从向量存储中删除文档,您可以使用文档本身。在 VectorStore 初始化期间提供的内容列和元数据列将用于查找与文档对应的行。任何匹配的行都将被删除。

db.delete(documents=[documents[0], documents[1]])