> ## 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.

# Gemini Enterprise Agent Platform 上的向量搜索集成

> 使用 LangChain 与 Gemini Enterprise Agent Platform 上的 Vector Search 向量存储集成。

本页面介绍如何在Gemini企业级智能体平台（Gemini Enterprise Agent Platform）上使用Vector Search作为LangChain的向量存储。

## 概述

[Vector Search on Gemini Enterprise Agent Platform](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search/overview) 是一种完全托管、高扩展、低延迟的解决方案，用于查找相似向量。它支持使用Google的ScaNN（Scalable Nearest Neighbors）技术进行精确和近似最近邻（ANN）搜索。

Vector Search on Gemini Enterprise Agent Platform提供两种版本：

* **[Vector Search 2.0](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search-2/overview)**: 使用Collections存储包含向量、元数据和内容的Data Objects。提供统一的数据模型和更简单快捷的操作。
* **[Vector Search 1.0](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search/overview)**: 部署Indexes到Endpoints，文档存储在Google Cloud Storage或Datastore中。

根据您使用的版本选择对应章节：

* [Vector Search 2.0](#vector-search-2-0) - 如果使用Collections
* [Vector Search 1.0](#vector-search-1-0) - 如果使用Indexes和Endpoints

从Vector Search on Gemini Enterprise Agent Platform 1.0迁移到2.0请参考[迁移指南](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search-2/migration-from-vs-1_0)。

## 安装

安装LangChain与Gemini企业级智能体平台的集成：

```bash theme={null}
pip install -U langchain-google-vertexai
```

***

# Vector Search 2.0

Vector Search 2.0使用Collections存储Data Objects。每个Data Object包含统一结构中的向量、元数据和内容。

## 前置条件

* 启用Gemini企业级智能体平台API和Vector Search API的Google Cloud项目
  ```bash theme={null}
  gcloud services enable vectorsearch.googleapis.com aiplatform.googleapis.com --project "{PROJECT_ID}"
  ```
* 创建Vector Search Collection（参见[创建Collection](#创建collection（v2）)）
* 适当的IAM权限（`Vertex AI User`角色或等效权限）

## 创建Collection（V2）

使用Vector Search 2.0前需创建Collection。以下是兼容LangChain的创建方法：

```python theme={null}
from google.cloud import vectorsearch_v1beta

# Configuration
PROJECT_ID = "your-project-id"
LOCATION = "us-central1"
COLLECTION_ID = "langchain-test-collection"

# Create the Vector Search service client
vector_search_service_client = vectorsearch_v1beta.VectorSearchServiceClient()

# Create the collection with schema compatible with LangChain
# IMPORTANT: To enable filtering, you must define filterable fields in data_schema.properties
request = vectorsearch_v1beta.CreateCollectionRequest(
    parent=f"projects/{PROJECT_ID}/locations/{LOCATION}",
    collection_id=COLLECTION_ID,
    collection={
        "display_name": "LangChain Test Collection",
        "description": "Collection for testing LangChain VectorSearchVectorStore with filtering",
        "data_schema": {
            "type": "object",
            "properties": {
                # Define fields you want to filter on
                "source": {"type": "string"},
                "category": {"type": "string"},
                "page": {"type": "number"},
                # Add more fields as needed for your specific use case
            },
        },
        "vector_schema": {
            # Vector field must be named "embedding" to match LangChain's default
            "embedding": {
                "dense_vector": {
                    "dimensions": 768  # For text-embedding-005
                }
            },
        },
    },
)

print(f"Creating collection: {COLLECTION_ID}")
operation = vector_search_service_client.create_collection(request=request)
print(f"Operation started: {operation.operation.name}")
print("Waiting for operation to complete...")

result = operation.result()
print(f"Collection created successfully!")
print(f"Resource name: {result.name}")
```

**重要说明：**

* 向量字段必须命名为`"embedding"`以匹配LangChain默认值（或通过`vector_field_name`参数指定）
* V2版本仅支持`data_schema.properties`中定义的字段进行过滤
* 维度应与嵌入模型匹配（768对于text-embedding-005）

## 初始化

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

# Initialize embeddings
embeddings = VertexAIEmbeddings(model_name="text-embedding-005")

# Create vector store from a Collection
# Use the same PROJECT_ID, LOCATION, and COLLECTION_ID from collection creation
vector_store = VectorSearchVectorStore.from_components(
    project_id=PROJECT_ID,
    region=LOCATION,
    collection_id=COLLECTION_ID,
    embedding=embeddings,
    api_version="v2",
)
```

**关键参数：**

* `collection_id`: Vector Search Collection ID（必填）
* `api_version`: 必须设置为`"v2"`（必填）
* `project_id`: GCP项目ID（必填）
* `region`: Collection所在的GCP区域（必填）
* `vector_field_name`: Collection schema中向量的字段名称（默认`"embedding"`）

## 添加文档

```python theme={null}
from langchain_core.documents import Document

# Create documents
docs = [
    Document(
        page_content="Gemini Enterprise Agent Platform is a managed machine learning platform",
        metadata={"source": "docs", "category": "AI"}
    ),
    Document(
        page_content="LangChain integrates with Vector Search on Gemini Enterprise Agent Platform",
        metadata={"source": "blog", "category": "integration"}
    ),
]

# Add documents to vector store
ids = vector_store.add_documents(docs)
print(f"Added documents with IDs: {ids}")
```

### 添加文本

```python theme={null}
texts = [
    "Gemini Enterprise Agent Platform provides scalable ML infrastructure",
    "Vector Search enables similarity search at scale",
]

metadatas = [
    {"source": "website", "page": 1},
    {"source": "website", "page": 2},
]

ids = vector_store.add_texts(texts=texts, metadatas=metadatas)
```

## 搜索

### 基本相似度搜索

```python theme={null}
# Basic similarity search
query = "What is Gemini Enterprise Agent Platform?"
results = vector_store.similarity_search(query, k=5)

for doc in results:
    print(f"Content: {doc.page_content}")
    print(f"Metadata: {doc.metadata}\n")
```

### 带分数的相似度搜索

```python theme={null}
# Get similarity scores along with documents
results_with_scores = vector_store.similarity_search_with_score(
    "What is Gemini Enterprise Agent Platform?",
    k=5
)

for doc, score in results_with_scores:
    print(f"Score: {score}")
    print(f"Content: {doc.page_content}")
    print(f"Metadata: {doc.metadata}\n")
```

### 通过向量搜索

```python theme={null}
# Search using a pre-computed embedding
embedding = embeddings.embed_query("Feature Store on Gemini Enterprise Agent Platform")

results = vector_store.similarity_search_by_vector_with_score(embedding, k=5)

for doc, score in results:
    print(f"Score: {score}")
    print(f"Content: {doc.page_content}\n")
```

## 过滤

Vector Search 2.0使用字典式查询语法进行Data Objects过滤：

```python theme={null}
# Simple equality filter
results = vector_store.similarity_search(
    "AI features",
    k=5,
    filter={"source": {"$eq": "docs"}}
)

# Comparison operators
results = vector_store.similarity_search(
    "recent pages",
    k=5,
    filter={"page": {"$gte": 10}}
)

# Logical AND
results = vector_store.similarity_search(
    "AI documentation",
    k=5,
    filter={
        "$and": [
            {"source": {"$eq": "docs"}},
            {"category": {"$eq": "AI"}}
        ]
    }
)

# Logical OR
results = vector_store.similarity_search(
    "documentation",
    k=5,
    filter={
        "$or": [
            {"source": {"$eq": "docs"}},
            {"source": {"$eq": "blog"}}
        ]
    }
)

# Less than
results = vector_store.similarity_search(
    "early pages",
    k=5,
    filter={"page": {"$lt": 5}}
)
```

**支持的操作符：**

* `$eq`: 等于
* `$ne`: 不等于
* `$lt`: 小于
* `$lte`: 小于或等于
* `$gt`: 大于
* `$gte`: 大于或等于
* `$and`: 逻辑AND
* `$or`: 逻辑OR
* `$not`: 逻辑NOT

See the [Vector Search 2.0 查询文档](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search-2/query-search/query) for more details.

## 删除操作

### 通过 IDs 删除

```python theme={null}
# Delete specific documents by ID
ids_to_delete = ["id1", "id2", "id3"]
vector_store.delete(ids=ids_to_delete)
```

### 通过元数据过滤器删除

**注意**: 当前 V2 API 中元数据删除存在限制。推荐方案为：

1. 使用 `similarity_search` 并结合您的过滤器获取文档 IDs
2. 通过 IDs 删除

```python theme={null}
# Recommended: Search first, then delete by IDs
results = vector_store.similarity_search(
    "query",  # Use a broad query
    k=1000,   # Get more results
    filter={"source": {"$eq": "old_docs"}}
)
ids_to_delete = [doc.metadata.get("id") for doc in results if "id" in doc.metadata]
vector_store.delete(ids=ids_to_delete)
```

或者，如果您的环境支持直接删除元数据：

```python theme={null}
# Direct deletion by metadata (may have limitations)
try:
    vector_store.delete(metadata={"source": {"$eq": "old_docs"}})
except Exception as e:
    # Fall back to search-then-delete approach
    print(f"Direct deletion failed: {e}")
```

## 高级功能

Vector Search 2.0 提供了超越传统密集向量搜索的多种高级搜索能力。

### 语义搜索

语义搜索会使用 Gemini 企业智能体平台模型从查询文本自动生成嵌入。您的集合必须配置 `vertex_embedding_config` 在向量方案中。

```python theme={null}
# Semantic search with auto-generated embeddings
results = vector_store.semantic_search(
    query="Tell me about animals",
    k=5,
    search_field="embedding",  # Vector field with auto-embedding config
    task_type="RETRIEVAL_QUERY",  # Optimizes embeddings for search queries
    filter={"category": {"$eq": "wildlife"}}  # Optional filtering
)

for doc in results:
    print(f"Content: {doc.page_content}")
    print(f"Metadata: {doc.metadata}\n")
```

**任务类型:**

* `RETRIEVAL_QUERY`: 查询搜索（默认）
* `RETRIEVAL_DOCUMENT`: 文档索引
* `SEMANTIC_SIMILARITY`: 语义相似度任务
* `CLASSIFICATION`: 分类任务
* `CLUSTERING`: 聚类任务

### 文本搜索

文本搜索会在数据字段中执行关键词/全文匹配，无需使用嵌入。

```python theme={null}
# Keyword search on data fields
results = vector_store.text_search(
    query="Python programming",
    k=10,
    data_field_names=["page_content", "title"]  # Fields to search in
)

for doc in results:
    print(f"Content: {doc.page_content}\n")
```

!!! note
文本搜索不支持过滤器。如需过滤请使用 `semantic_search()` 或 `similarity_search()`

### 混合搜索

混合搜索通过 reciprocity rank fusion（RRF）融合自动生成的语义搜索（基于嵌入）和文本搜索（关键词匹配），生成最优排序结果。

```python theme={null}
# Hybrid search: semantic understanding + keyword matching
results = vector_store.hybrid_search(
    query="Men's outfit for beach",
    k=10,
    search_field="embedding",  # Vector field with auto-embedding config
    data_field_names=["page_content"],  # Fields for text search
    task_type="RETRIEVAL_QUERY",
    filter={"price": {"$lt": 100}},  # Optional filter for semantic search
    semantic_weight=1.0,  # Weight for semantic results
    text_weight=1.0  # Weight for keyword results
)

for doc in results:
    print(f"Content: {doc.page_content}\n")
```

**权重参数:**

* 更高的 `semantic_weight`: 优先语义理解
* 更高的 `text_weight`: 优先精确关键词匹配
* 相等权重（默认）：平衡结果

在语义和文本搜索结果中排名均靠前的项目，将在合并结果中排名最高。

See the [Vector Search 2.0 文档](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search-2/overview) for more information.

### 自定义向量字段名

如果您的集合方案使用自定义向量字段名：

```python theme={null}
vector_store = VectorSearchVectorStore.from_components(
    project_id="your-project-id",
    region="us-central1",
    collection_id="your-collection-id",
    embedding=embeddings,
    api_version="v2",
    vector_field_name="custom_embedding_field",  # Match your schema
)
```

## 补充资源

* [Vector Search 2.0 概览](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search-2/overview)
* [Vector Search 2.0 集合](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search-2/collections/collections)
* [Vector Search 2.0 数据对象](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search-2/data-objects/data-objects)
* [Vector Search 2.0 搜索指南](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search-2/query-search/search)
* [Vector Search 2.0 查询指南](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search-2/query-search/query)
* [Vector Search 2.0 迁移指南](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search-2/migration-from-vs-1_0)

***

# Vector Search 1.0

本笔记本演示如何使用 `Google Cloud Vector Search on Gemini Enterprise Agent Platform` 向量数据库相关功能。

> [Gemini 企业智能体平台上的 Vector Search](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search/overview)，前身为 Vertex AI 匹配引擎，提供业界领先的规模化低延迟向量数据库。这些向量数据库通常被称为向量相似匹配或近似最近邻（ANN）服务。

**注意**: LangChain API 需要预先创建端点及部署的索引。索引创建时间可能长达一小时。

> 参见 [创建索引并将其部署到端点](#创建索引并部署到端点) 了解如何创建索引
> 如果已部署索引，请跳转到 [从文本创建 VectorStore](#从文本创建向量存储)

## 创建索引并部署到端点

* 本节演示如何创建新索引并部署到端点

```python theme={null}
# TODO : Set values as per your requirements
# Project and Storage Constants
PROJECT_ID = "<my_project_id>"
REGION = "<my_region>"
BUCKET = "<my_gcs_bucket>"
BUCKET_URI = f"gs://{BUCKET}"

# The number of dimensions for the textembedding-gecko@003 is 768
# If other embedder is used, the dimensions would probably need to change.
DIMENSIONS = 768

# Index Constants
DISPLAY_NAME = "<my_matching_engine_index_id>"
DEPLOYED_INDEX_ID = "<my_matching_engine_endpoint_id>"
```

```python theme={null}
# Create a bucket.
! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI
```

### 使用 `VertexAIEmbeddings` 作为嵌入模型

```python theme={null}
from google.cloud import aiplatform
from langchain_google_vertexai import VertexAIEmbeddings
```

```python theme={null}
aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_URI)
```

```python theme={null}
embedding_model = VertexAIEmbeddings(model_name="text-embedding-005")
```

### 创建空索引

**注意**：创建索引时需指定 "index\_update\_method" 参数，其取值范围为 "BATCH\_UPDATE" 或 "STREAM\_UPDATE"

> 批量索引适用于需要按固定周期（如每周或每月）更新索引的场景，例如系统处理周期性存储的数据。流式索引则适用于实时更新场景，例如书店需即时展示新库存信息。选择索引更新方式直接影响系统配置和运行要求。

参考 [官方文档](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search/create-manage-index#create-index-batch) 获取索引配置的详细信息

```python theme={null}
# NOTE : This operation can take upto 30 seconds
my_index = aiplatform.MatchingEngineIndex.create_tree_ah_index(
    display_name=DISPLAY_NAME,
    dimensions=DIMENSIONS,
    approximate_neighbors_count=150,
    distance_measure_type="DOT_PRODUCT_DISTANCE",
    index_update_method="STREAM_UPDATE",  # allowed values BATCH_UPDATE , STREAM_UPDATE
)
```

### 创建端点

```python theme={null}
# Create an endpoint
my_index_endpoint = aiplatform.MatchingEngineIndexEndpoint.create(
    display_name=f"{DISPLAY_NAME}-endpoint", public_endpoint_enabled=True
)
```

### 部署索引到端点

```python theme={null}
# NOTE : This operation can take upto 20 minutes
my_index_endpoint = my_index_endpoint.deploy_index(
    index=my_index, deployed_index_id=DEPLOYED_INDEX_ID
)

my_index_endpoint.deployed_indexes
```

## 从文本创建向量存储

NOTE：若已有索引和端点，可通过以下代码加载

```python theme={null}
# TODO : replace 1234567890123456789 with your actual index ID
my_index = aiplatform.MatchingEngineIndex("1234567890123456789")

# TODO : replace 1234567890123456789 with your actual endpoint ID
my_index_endpoint = aiplatform.MatchingEngineIndexEndpoint("1234567890123456789")
```

```python theme={null}
from langchain_google_vertexai import (
    VectorSearchVectorStore,
    VectorSearchVectorStoreDatastore,
)
```

![Langchainassets.png](https://mintlify.s3.us-west-1.amazonaws.com/langchain-docs-zh/images/integrations/vertex-ai-vector-search.png)

### 创建简单向量存储（无过滤）

```python theme={null}
# Input texts
texts = [
    "The cat sat on",
    "the mat.",
    "I like to",
    "eat pizza for",
    "dinner.",
    "The sun sets",
    "in the west.",
]

# Create a Vector Store
vector_store = VectorSearchVectorStore.from_components(
    project_id=PROJECT_ID,
    region=REGION,
    gcs_bucket_name=BUCKET,
    index_id=my_index.name,
    endpoint_id=my_index_endpoint.name,
    embedding=embedding_model,
    stream_update=True,
)

# Add vectors and mapped text chunks to your vector store
vector_store.add_texts(texts=texts)
```

### OPTIONAL : 您也可以创建向量并存储到数据存储中

```python theme={null}
# NOTE : This operation can take upto 20 mins
vector_store = VectorSearchVectorStoreDatastore.from_components(
    project_id=PROJECT_ID,
    region=REGION,
    index_id=my_index.name,
    endpoint_id=my_index_endpoint.name,
    embedding=embedding_model,
    stream_update=True,
)

vector_store.add_texts(texts=texts, is_complete_overwrite=True)
```

```python theme={null}
# Try running a simialarity search
vector_store.similarity_search("pizza")
```

### 使用元数据过滤器创建向量存储

```python theme={null}
# Input text with metadata
record_data = [
    {
        "description": "A versatile pair of dark-wash denim jeans."
        "Made from durable cotton with a classic straight-leg cut, these jeans"
        " transition easily from casual days to dressier occasions.",
        "price": 65.00,
        "color": "blue",
        "season": ["fall", "winter", "spring"],
    },
    {
        "description": "A lightweight linen button-down shirt in a crisp white."
        " Perfect for keeping cool with breathable fabric and a relaxed fit.",
        "price": 34.99,
        "color": "white",
        "season": ["summer", "spring"],
    },
    {
        "description": "A soft, chunky knit sweater in a vibrant forest green. "
        "The oversized fit and cozy wool blend make this ideal for staying warm "
        "when the temperature drops.",
        "price": 89.99,
        "color": "green",
        "season": ["fall", "winter"],
    },
    {
        "description": "A classic crewneck t-shirt in a soft, heathered blue. "
        "Made from comfortable cotton jersey, this t-shirt is a wardrobe essential "
        "that works for every season.",
        "price": 19.99,
        "color": "blue",
        "season": ["fall", "winter", "summer", "spring"],
    },
    {
        "description": "A flowing midi-skirt in a delicate floral print. "
        "Lightweight and airy, this skirt adds a touch of feminine style "
        "to warmer days.",
        "price": 45.00,
        "color": "white",
        "season": ["spring", "summer"],
    },
]
```

```python theme={null}
# Parse and prepare input data

texts = []
metadatas = []
for record in record_data:
    record = record.copy()
    page_content = record.pop("description")
    texts.append(page_content)
    if isinstance(page_content, str):
        metadata = {**record}
        metadatas.append(metadata)
```

```python theme={null}
# Inspect metadatas
metadatas
```

```python theme={null}
# NOTE : This operation can take more than 20 mins
vector_store = VectorSearchVectorStore.from_components(
    project_id=PROJECT_ID,
    region=REGION,
    gcs_bucket_name=BUCKET,
    index_id=my_index.name,
    endpoint_id=my_index_endpoint.name,
    embedding=embedding_model,
)

vector_store.add_texts(texts=texts, metadatas=metadatas, is_complete_overwrite=True)
```

```python theme={null}
from google.cloud.aiplatform.matching_engine.matching_engine_index_endpoint import (
    Namespace,
    NumericNamespace,
)
```

```python theme={null}
# Try running a simple similarity search

# Below code should return 5 results
vector_store.similarity_search("shirt", k=5)
```

```python theme={null}
# Try running a similarity search with text filter
filters = [Namespace(name="season", allow_tokens=["spring"])]

# Below code should return 4 results now
vector_store.similarity_search("shirt", k=5, filter=filters)
```

```python theme={null}
# Try running a similarity search with combination of text and numeric filter
filters = [Namespace(name="season", allow_tokens=["spring"])]
numeric_filters = [NumericNamespace(name="price", value_float=40.0, op="LESS")]

# Below code should return 2 results now
vector_store.similarity_search(
    "shirt", k=5, filter=filters, numeric_filter=numeric_filters
)
```

### 将向量存储用作检索器

```python theme={null}
# Initialize the vectore_store as retriever
retriever = vector_store.as_retriever()
```

```python theme={null}
# perform simple similarity search on retriever
retriever.invoke("What are my options in breathable fabric?")
```

```python theme={null}
# Try running a similarity search with text filter
filters = [Namespace(name="season", allow_tokens=["spring"])]

retriever.search_kwargs = {"filter": filters}

# perform similarity search with filters on retriever
retriever.invoke("What are my options in breathable fabric?")
```

```python theme={null}
# Try running a similarity search with combination of text and numeric filter
filters = [Namespace(name="season", allow_tokens=["spring"])]
numeric_filters = [NumericNamespace(name="price", value_float=40.0, op="LESS")]


retriever.search_kwargs = {"filter": filters, "numeric_filter": numeric_filters}

retriever.invoke("What are my options in breathable fabric?")
```

### 在问答链中使用过滤器与检索器

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

llm = VertexAI(model_name="gemini-3.6-flash")
```

```python theme={null}
from langchain_classic.chains import RetrievalQA

filters = [Namespace(name="season", allow_tokens=["spring"])]
numeric_filters = [NumericNamespace(name="price", value_float=40.0, op="LESS")]

retriever.search_kwargs = {"k": 2, "filter": filters, "numeric_filter": numeric_filters}

retrieval_qa = RetrievalQA.from_chain_type(
    llm=llm,
    chain_type="stuff",
    retriever=retriever,
    return_source_documents=True,
)

question = "What are my options in breathable fabric?"
response = retrieval_qa({"query": question})
print(f"{response['result']}")
print("REFERENCES")
print(f"{response['source_documents']}")
```

## 读取、分块、向量化并索引PDF文件

```python theme={null}
!pip install pypdf
```

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

```python theme={null}
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
```

```python theme={null}
loader = PyPDFLoader("https://arxiv.org/pdf/1706.03762.pdf")
pages = loader.load()
```

```python theme={null}
text_splitter = RecursiveCharacterTextSplitter(
    # Set a really small chunk size, just to show.
    chunk_size=1000,
    chunk_overlap=20,
    length_function=len,
    is_separator_regex=False,
)
doc_splits = text_splitter.split_documents(pages)
```

```python theme={null}
texts = [doc.page_content for doc in doc_splits]
metadatas = [doc.metadata for doc in doc_splits]
```

```python theme={null}
texts[0]
```

```python theme={null}
# Inspect Metadata of 1st page
metadatas[0]
```

```python theme={null}
vector_store = VectorSearchVectorStore.from_components(
    project_id=PROJECT_ID,
    region=REGION,
    gcs_bucket_name=BUCKET,
    index_id=my_index.name,
    endpoint_id=my_index_endpoint.name,
    embedding=embedding_model,
)

vector_store.add_texts(texts=texts, metadatas=metadatas, is_complete_overwrite=True)
```

```python theme={null}
vector_store = VectorSearchVectorStore.from_components(
    project_id=PROJECT_ID,
    region=REGION,
    gcs_bucket_name=BUCKET,
    index_id=my_index.name,
    endpoint_id=my_index_endpoint.name,
    embedding=embedding_model,
)
```

## 混合搜索

向量搜索支持混合搜索（Hybrid Search），这是一种在信息检索（IR）中广泛使用的架构模式，结合了语义搜索和关键词搜索（也称为基于令牌的搜索）。通过混合搜索，开发者可以同时利用两种方法的优点，从而提供更高质量的内容检索。

请阅读 [Gemini 企业智能体平台混合搜索文档](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/vector-search/about-hybrid-search) 以了解更多信息。

要使用混合搜索，我们需要适配一个稀疏嵌入向量izer，并独立处理嵌入过程（不依赖于Vector Search集成）。

稀疏嵌入向量izer的一个示例是sklearn的TfidfVectorizer，但也可以使用其他技术，例如BM25。

```python theme={null}
# Define some sample data
texts = [
    "The cat sat on",
    "the mat.",
    "I like to",
    "eat pizza for",
    "dinner.",
    "The sun sets",
    "in the west.",
]

# optional IDs
ids = ["i_" + str(i + 1) for i in range(len(texts))]

# optional metadata
metadatas = [{"my_metadata": i} for i in range(len(texts))]
```

```python theme={null}
from sklearn.feature_extraction.text import TfidfVectorizer

# Fit the TFIDF Vectorizer (This is usually done on a very large corpus of data to make sure that word statistics generalize well on new data)
vectorizer = TfidfVectorizer()
vectorizer.fit(texts)
```

```python theme={null}
# Utility function to transform text into a TF-IDF Sparse Vector
def get_sparse_embedding(tfidf_vectorizer, text):
    tfidf_vector = tfidf_vectorizer.transform([text])
    values = []
    dims = []
    for i, tfidf_value in enumerate(tfidf_vector.data):
        values.append(float(tfidf_value))
        dims.append(int(tfidf_vector.indices[i]))
    return {"values": values, "dimensions": dims}
```

```python theme={null}
# semantic (dense) embeddings
embeddings = embedding_model.embed_documents(texts)
# tfidf (sparse) embeddings
sparse_embeddings = [get_sparse_embedding(vectorizer, x) for x in texts]
```

```python theme={null}
sparse_embeddings[0]
```

```python theme={null}
# Add the dense and sparse embeddings in Vector Search

vector_store.add_texts_with_embeddings(
    texts=texts,
    embeddings=embeddings,
    sparse_embeddings=sparse_embeddings,
    ids=ids,
    metadatas=metadatas,
)
```

```python theme={null}
# Run hybrid search
query = "the cat"
embedding = embedding_model.embed_query(query)
sparse_embedding = get_sparse_embedding(vectorizer, query)

vector_store.similarity_search_by_vector_with_score(
    embedding=embedding,
    sparse_embedding=sparse_embedding,
    k=5,
    rrf_ranking_alpha=0.7,  # 0.7 weight to dense and 0.3 weight to sparse
)
```

***

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


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