以编程方式使用文档

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

本笔记本介绍如何使用 Spanner 进行向量搜索与 SpannerVectorStore class.

了解更多关于该包的信息,请访问 GitHub.

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

准备工作

要运行本笔记本,您需要完成以下步骤:

🦜🔗 库安装

该集成位于其独立的 langchain-google-spanner 包中,因此我们需要安装它。

pip install -qU langchain-google-spanner 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)

🔐 身份验证

作为登录本笔记本的 IAM 用户向 Google Cloud 进行身份验证,以访问您的 Google Cloud 项目。

  • * 如果您使用 Colab 运行本笔记本,请使用下面的单元格并继续。
  • * 如果您使用 Vertex AI Workbench,请查看 Vertex AI Workbench 设置说明.
from google.colab import auth

auth.authenticate_user()

☁ 设置您的 Google Cloud 项目

设置您的 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 软件包要求您 启用 Spanner API 在您的 Google Cloud 项目中。

# 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"}

初始化表

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
)

SpannerVectorStore

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

  1. instance_id - 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"],
)

添加文档

用于在向量存储中添加文档

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)

搜索文档

用于在向量存储中进行相似性搜索

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

搜索文档

用于在向量存储中进行最大边际相关性搜索

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

删除文档

要从向量存储中移除文档,请使用与对应的值 row_id列中的ID值。初始化VectorStore时会用到这些列

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

删除文档

要从向量存储中删除文档,您可以直接使用文档本身。系统会根据初始化VectorStore时提供的内容列和元数据列来定位对应的行,然后删除所有匹配的行

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