> ## 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 Spanner 集成

> 使用 LangChain Python 与 Google spanner 向量存储集成。

> [Spanner](https://cloud.google.com/spanner) 是一个高度可扩展的数据库，结合了无限扩展性与关系型语义，例如次级索引、强一致性、模式定义和SQL，提供99.999%可用性的单一解决方案。

本笔记本将介绍如何使用 `Spanner` 进行向量搜索，并配合 `SpannerVectorStore` 类实现。

了解该包的更多信息请参考 [GitHub](https://github.com/googleapis/langchain-google-spanner-python/)。

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/googleapis/langchain-google-spanner-python/blob/main/docs/vector_store.ipynb)

## 开始前

运行本笔记本前需要完成以下步骤：

* [创建Google Cloud项目](https://developers.google.com/workspace/guides/create-project)
* [启用Cloud Spanner API](https://console.cloud.google.com/flows/enableapi?apiid=spanner.googleapis.com)
* [创建Spanner实例](https://cloud.google.com/spanner/docs/create-manage-instances)
* [创建Spanner数据库](https://cloud.google.com/spanner/docs/create-manage-databases)

### 🦜🔗 库安装

集成模块位于独立的 `langchain-google-spanner` 包中，因此需要安装该包。

```python theme={null}
pip install -qU langchain-google-spanner langchain-google-vertexai
```

**Colab专用**：取消注释以下单元格以重启内核或使用重启按钮。对于Gemini企业智能体平台工作台，请使用顶部按钮重启终端。

```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)
```

### 🔐 认证

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

* 若使用Colab运行本笔记本，请使用下方单元格继续。
* 若使用Gemini企业智能体平台工作台，请查阅 [Gemini企业智能体平台工作台设置指南](https://github.com/GoogleCloudPlatform/generative-ai/tree/main/setup-env)。

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

auth.authenticate_user()
```

### ☁ 设置Google云项目

在本笔记本中设置您的Google云项目，以便使用Google云资源。

若不知道项目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}
%env GOOGLE_CLOUD_PROJECT={PROJECT_ID}
```

### 💡 API启用

`langchain-google-spanner` 包需要您在Google Cloud项目中 [启用Spanner API](https://console.cloud.google.com/flows/enableapi?apiid=spanner.googleapis.com)。

```python theme={null}
# enable Spanner API
!gcloud services enable spanner.googleapis.com
```

## 基础用法

### 设置Spanner数据库值

在 [Spanner实例页面](https://console.cloud.google.com/spanner?_ga=2.223735448.2062268965.1707700487-2088871159.1707257687) 中查找您的数据库值。

```python theme={null}
# @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()` 来创建具有正确模式的表。

```python theme={null}
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嵌入模型](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings.md)。
若需使用 `VertexAIEmbeddings`，可能需要启用Gemini企业智能体平台API。我们建议为生产环境设置嵌入模型的版本，更多详情请参考 [文本嵌入模型](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/models/text-embeddings-api)。

```python theme={null}
# enable Gemini Enterprise Agent Platform API
!gcloud services enable aiplatform.googleapis.com
```

```python theme={null}
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实现

```python theme={null}
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"],
)
```

#### 添加文档

向向量存储中添加文档。

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

```python theme={null}
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)
```

#### 搜索文档

使用相似度搜索在向量存储中检索文档。

```python theme={null}
db.similarity_search(query="Explain me vector store?", k=3)
```

#### 搜索文档

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

```python theme={null}
db.max_marginal_relevance_search("Testing the langchain integration with spanner", k=3)
```

#### 删除文档

从向量存储中移除文档，需使用初始化VectorStore时设置的 `row_id` 字段对应的ID。

```python theme={null}
db.delete(ids=["id1", "id2"])
```

#### 删除文档

可通过文档本身删除向量存储中的文档。VectorStore初始化时提供的content字段和元数据字段将用于查找对应行，所有匹配行将被删除。

```python theme={null}
db.delete(documents=[documents[0], documents[1]])
```

***

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


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