跳到主要內容
Open In ColabOpen on GitHub

Google BigQuery 向量搜尋

Google Cloud BigQuery 向量搜尋 讓您可以使用 GoogleSQL 進行語意搜尋,使用向量索引以獲得快速近似結果,或使用暴力搜尋以獲得精確結果。

本教學說明如何在 LangChain 中使用端對端資料和嵌入管理系統,並使用 BigQueryVectorStore 類別在 BigQuery 中提供可擴展的語意搜尋。此類別是 2 個類別集合的一部分,能夠在 Google Cloud 中提供統一的資料儲存和彈性的向量搜尋

  • BigQuery 向量搜尋:使用 BigQueryVectorStore 類別,非常適合無需基礎架構設定和批次檢索的快速原型設計。
  • Feature Store Online Store:使用 VertexFSVectorStore 類別,可透過手動或排程資料同步實現低延遲檢索。非常適合生產就緒、面向使用者的 GenAI 應用程式。

Diagram BQ-VertexFS

開始使用

安裝程式庫

%pip install --upgrade --quiet  langchain langchain-google-vertexai "langchain-google-community[featurestore]"

若要在這個 Jupyter 執行階段中使用新安裝的套件,您必須重新啟動執行階段。您可以執行以下儲存格來執行此操作,這會重新啟動目前的核心。

import IPython

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

開始之前

設定您的專案 ID

如果您不知道您的專案 ID,請嘗試以下操作

  • 執行 gcloud config list
  • 執行 gcloud projects list
  • 請參閱支援頁面:尋找專案 ID
PROJECT_ID = ""  # @param {type:"string"}

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

設定區域

您也可以變更 BigQuery 使用的 REGION 變數。深入瞭解 BigQuery 區域

REGION = "us-central1"  # @param {type: "string"}

設定資料集和表格名稱

它們將會是您的 BigQuery 向量儲存。

DATASET = "my_langchain_dataset"  # @param {type: "string"}
TABLE = "doc_and_vectors" # @param {type: "string"}

驗證您的 Notebook 環境

  • 如果您使用 Colab 執行此 Notebook,請取消註解下方的儲存格並繼續。
  • 如果您使用 Vertex AI Workbench,請查看此處的設定指示 here
# from google.colab import auth as google_auth

# google_auth.authenticate_user()

Demo:BigQueryVectorStore

建立嵌入類別實例

您可能需要在您的專案中啟用 Vertex AI API,方法是執行 gcloud services enable aiplatform.googleapis.com --project {PROJECT_ID} (將 {PROJECT_ID} 替換為您的專案名稱)。

您可以使用任何 LangChain 嵌入模型

from langchain_google_vertexai import VertexAIEmbeddings

embedding = VertexAIEmbeddings(
model_name="textembedding-gecko@latest", project=PROJECT_ID
)
API 參考:VertexAIEmbeddings

初始化 BigQueryVectorStore

如果 BigQuery 資料集和表格不存在,將會自動建立。如需所有選用參數,請參閱此處的類別定義 here

from langchain_google_community import BigQueryVectorStore

store = BigQueryVectorStore(
project_id=PROJECT_ID,
dataset_name=DATASET,
table_name=TABLE,
location=REGION,
embedding=embedding,
)
API 參考:BigQueryVectorStore

新增文字

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)

搜尋文件

query = "I'd like a fruit."
docs = store.similarity_search(query)
print(docs)

依向量搜尋文件

query_vector = embedding.embed_query(query)
docs = store.similarity_search_by_vector(query_vector, k=2)
print(docs)

使用中繼資料篩選器搜尋文件

vectorstore 支援兩種方法,可在執行文件搜尋時將篩選器套用至中繼資料欄位

  • 基於字典的篩選器
    • 您可以傳遞字典 (dict),其中鍵代表中繼資料欄位,而值指定篩選條件。此方法會套用鍵與對應值之間的相等篩選器。當提供多個鍵值對時,它們會使用邏輯 AND 運算結合。
  • 基於 SQL 的篩選器
    • 或者,您可以提供代表 SQL WHERE 子句的字串,以定義更複雜的篩選條件。這允許更大的彈性,支援 SQL 表達式,例如比較運算子和邏輯運算子。深入瞭解 BigQuery 運算子
# Dictionary-based Filters
# This should only return "Banana" document.
docs = store.similarity_search_by_vector(query_vector, filter={"len": 6})
print(docs)
# 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 方法,用於可擴展的向量相似度搜尋。

results = store.batch_search(
embeddings=None, # can pass embeddings or
queries=["search_query", "search_query"], # can pass queries
)

新增具有嵌入的文字

您也可以使用 add_texts_with_embeddings 方法攜帶您自己的嵌入。這對於多模態資料特別有用,這些資料可能需要在嵌入產生之前進行自訂預處理。

items = ["some text"]
embs = embedding.embed(items)

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

使用 Feature Store 進行低延遲服務

您可以簡單地使用 .to_vertex_fs_vector_store() 方法來取得 VertexFSVectorStore 物件,這為線上使用案例提供低延遲。所有必要參數都將自動從現有的 BigQueryVectorStore 類別傳輸。如需您可以使用的所有其他參數,請參閱 類別定義

使用 .to_bq_vector_store() 方法可以同樣輕鬆地移回 BigQueryVectorStore。

store.to_vertex_fs_vector_store()  # pass optional VertexFSVectorStore parameters as arguments

此頁面是否有幫助?