> ## 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 BigQuery 向量搜索集成

> 使用 LangChain Python 与 Google bigquery 向量搜索向量存储集成。

> [Google Cloud BigQuery Vector Search](https://cloud.google.com/bigquery/docs/vector-search-intro) 允许您使用 GoogleSQL 进行语义搜索，利用向量索引实现快速近似结果，或使用暴力搜索实现精确结果。

本教程展示了如何在 LangChain 中使用端到端的数据和嵌入管理系统，并使用`BigQueryVectorStore`类在 BigQuery 中实现可扩展的语义搜索。该类是 Google Cloud 中一组 2 个类的一部分，能够提供统一的数据存储和灵活的向量搜索：

* **BigQuery Vector Search**：使用 `BigQueryVectorStore`类，适用于无需基础设施设置即可快速原型设计的批量检索。
* **Feature Store Online Store**：使用 `VertexFSVectorStore`类，支持手动或计划数据同步的低延迟检索。非常适合生产就绪的用户界面 GenAI 应用。

![Diagram BQ-VertexFS](https://mintlify.s3.us-west-1.amazonaws.com/langchain-docs-zh/images/integrations/bigquery-vertex-feature-store.png)

## 入门指南

### 安装库

```python theme={null}
pip install -qU  langchain langchain-google-vertexai "langchain-google-community[featurestore]"
```

要在 Jupyter 运行时中使用新安装的包，您必须重启运行时。您可以通过运行下面的单元格来重启当前内核。

```python theme={null}
import IPython

app = IPython.Application.instance()
app.kernel.do_shutdown(True)
```

## 开始前

#### 设置您的项目 ID

如果您不知道您的项目 ID，请尝试以下方法：

* 运行 `gcloud config list`。
* 运行 `gcloud projects list`。
* 查看支持页面：[定位项目 ID](https://support.google.com/googleapi/answer/7014113)。

```python theme={null}
PROJECT_ID = ""  # @param {type:"string"}

# Set the project id
! gcloud config set project {PROJECT_ID}
```

#### 设置区域

您还可以更改 BigQuery 使用的 `REGION` 变量。了解更多关于 [BigQuery 区域](https://cloud.google.com/bigquery/docs/locations#supported_locations) 的信息。

```python theme={null}
REGION = "us-central1"  # @param {type: "string"}
```

#### 设置数据集和表名

它们将作为您的 BigQuery 向量存储。

```python theme={null}
DATASET = "my_langchain_dataset"  # @param {type: "string"}
TABLE = "doc_and_vectors"  # @param {type: "string"}
```

### 认证您的笔记本环境

* 如果您使用 **Colab** 运行此笔记本，请取消注释下面的单元格并继续。
* 如果您使用 **Gemini Enterprise Agent Platform Workbench**，请查看 [Gemini Enterprise Agent Platform Workbench 设置说明](https://github.com/GoogleCloudPlatform/generative-ai/tree/main/setup-env)。

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

# google_auth.authenticate_user()
```

## 示例：BigQueryVectorStore

### 创建嵌入类实例

您可能需要通过运行
`gcloud services enable aiplatform.googleapis.com --project {PROJECT_ID}`
（将 `{PROJECT_ID}` 替换为您的项目名称）来在您的项目中启用 Gemini Enterprise Agent Platform API。

您可以使用任何 [LangChain 嵌入模型](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/embeddings.md)。

```python theme={null}
from langchain_google_vertexai import VertexAIEmbeddings

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

### 初始化 BigQueryVectorStore

如果 BigQuery 数据集和表不存在，它们将自动创建。查看 [类定义](https://github.com/langchain-ai/langchain-google/blob/main/libs/community/langchain_google_community/bq_storage_vectorstores/bigquery.py#L26) 了解所有可选参数。

```python theme={null}
from langchain_google_community import BigQueryVectorStore

store = BigQueryVectorStore(
    project_id=PROJECT_ID,
    dataset_name=DATASET,
    table_name=TABLE,
    location=REGION,
    embedding=embedding,
)
```

### 添加文本

```python theme={null}
all_texts = ["Apples and oranges", "Cars and airplanes", "Pineapple", "Train", "Banana"]
metadatas = [{"len": len(t)} for t in all_texts]

store.add_texts(all_texts, metadatas=metadatas)
```

### 搜索文档

```python theme={null}
query = "I'd like a fruit."
docs = store.similarity_search(query)
print(docs)
```

### 通过向量搜索文档

```python theme={null}
query_vector = embedding.embed_query(query)
docs = store.similarity_search_by_vector(query_vector, k=2)
print(docs)
```

### 带元数据过滤器的文档搜索

向量存储支持两种方法在执行文档搜索时对元数据字段应用过滤器：

* 基于字典的过滤器
  * 您可以传递一个字典（dict），其中键表示元数据字段，值指定过滤条件。此方法在键和相应值之间应用等式过滤器。当提供多个键值对时，它们使用逻辑 AND 操作组合。
* 基于 SQL 的过滤器
  * 或者，您可以提供一个表示 SQL WHERE 子句的字符串来定义更复杂的过滤条件。这提供了更大的灵活性，支持 SQL 表达式，如比较运算符和逻辑运算符。了解更多关于 [BigQuery 运算符](https://cloud.google.com/bigquery/docs/reference/standard-sql/operators) 的信息。

```python theme={null}
# Dictionary-based Filters
# This should only return "Banana" document.
docs = store.similarity_search_by_vector(query_vector, filter={"len": 6})
print(docs)
```

```python theme={null}
# SQL-based Filters
# This should return "Banana", "Apples and oranges" and "Cars and airplanes" documents.
docs = store.similarity_search_by_vector(query_vector, filter="len = 6 AND len > 17")
print(docs)
```

### 批量搜索

BigQueryVectorStore 提供了一个 `batch_search` 方法，用于可扩展的向量相似性搜索。

```python theme={null}
results = store.batch_search(
    embeddings=None,  # can pass embeddings or
    queries=["search_query", "search_query"],  # can pass queries
)
```

### 带嵌入的文本添加

您也可以使用 `add_texts_with_embeddings` 方法添加自己的嵌入。
这对于可能需要在嵌入生成之前进行自定义预处理的多模态数据特别有用。

```python theme={null}
items = ["some text"]
embs = embedding.embed(items)

ids = store.add_texts_with_embeddings(
    texts=["some text"], embs=embs, metadatas=[{"len": 1}]
)
```

### 使用特征存储的低延迟服务

您只需使用方法 `.to_vertex_fs_vector_store()` 获取 VertexFSVectorStore 对象，它为在线用例提供低延迟。所有必填参数将自动从现有的 BigQueryVectorStore 类中传输。查看 [类定义](https://github.com/langchain-ai/langchain-google/blob/main/libs/community/langchain_google_community/bq_storage_vectorstores/featurestore.py#L33) 了解您可以使用的其他参数。

回到 BigQueryVectorStore 同样容易，只需使用 `.to_bq_vector_store()` 方法即可。

```python theme={null}
store.to_vertex_fs_vector_store()  # pass optional VertexFSVectorStore parameters as arguments
```

***

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


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