跳至主要內容

DatabricksVectorSearch

Databricks Vector Search 是一個無伺服器相似度搜尋引擎,可讓您將資料的向量表示(包括中繼資料)儲存在向量資料庫中。透過 Vector Search,您可以從 Unity Catalog 管理的 Delta 表建立自動更新的向量搜尋索引,並使用簡單的 API 查詢它們以傳回最相似的向量。

此筆記本示範如何將 LangChain 與 Databricks Vector Search 搭配使用。

設定 (Setup)

若要存取 Databricks 模型,您需要建立 Databricks 帳戶、設定認證 (僅當您在 Databricks 工作區外部時) 並安裝必要的套件。

認證 (僅當您在 Databricks 外部時) (Credentials (only if you are outside Databricks))

如果您在 Databricks 內部執行 LangChain 應用程式,則可以跳過此步驟。

否則,您需要手動將 Databricks 工作區主機名稱和個人存取權杖分別設定為 DATABRICKS_HOSTDATABRICKS_TOKEN 環境變數。請參閱驗證文件,瞭解如何取得存取權杖。

import getpass
import os

os.environ["DATABRICKS_HOST"] = "https://your-databricks-workspace"
if "DATABRICKS_TOKEN" not in os.environ:
os.environ["DATABRICKS_TOKEN"] = getpass.getpass(
"Enter your Databricks access token: "
)

安裝 (Installation)

LangChain Databricks 整合位於 databricks-langchain 套件中。

%pip install -qU databricks-langchain

建立 Vector Search 端點和索引 (如果您尚未建立) (Create a Vector Search Endpoint and Index (if you haven't already))

在本節中,我們將使用用戶端 SDK 建立 Databricks Vector Search 端點和索引。

如果您已經有端點和索引,則可以跳過本節並直接前往「實例化 (Instantiation)」章節。

首先,實例化 Databricks VectorSearch 用戶端

from databricks.vector_search.client import VectorSearchClient

client = VectorSearchClient()

接下來,我們將建立新的 VectorSearch 端點。

endpoint_name = "<your-endpoint-name>"

client.create_endpoint(name=endpoint_name, endpoint_type="STANDARD")

最後,我們將建立可在端點上查詢的索引。Databricks Vector Search 中有兩種類型的索引,DatabricksVectorSearch 類別支援這兩種使用案例。

  • Delta 同步索引 (Delta Sync Index) 會自動與來源 Delta 表同步,並在 Delta 表中的基礎資料變更時自動且漸進式地更新索引。

  • 直接向量存取索引 (Direct Vector Access Index) 支援向量和中繼資料的直接讀取和寫入。使用者負責使用 REST API 或 Python SDK 更新此表。

此外,對於 delta-sync 索引,您可以選擇使用 Databricks 管理的嵌入或自行管理的嵌入 (透過 LangChain 嵌入類別)。

以下程式碼建立直接存取 (direct-access)索引。有關建立其他類型索引的說明,請參閱Databricks 文件

index_name = "<your-index-name>"  # Format: "<catalog>.<schema>.<index-name>"

index = client.create_direct_access_index(
endpoint_name=endpoint_name,
index_name=index_name,
primary_key="id",
# Dimension of the embeddings. Please change according to the embedding model you are using.
embedding_dimension=3072,
# A column to store the embedding vectors for the text data
embedding_vector_column="text_vector",
schema={
"id": "string",
"text": "string",
"text_vector": "array<float>",
# Optional metadata columns
"source": "string",
},
)

index.describe()

實例化 (Instantiation)

DatabricksVectorSearch 的實例化方式略有不同,具體取決於您的索引是使用 Databricks 管理的嵌入還是自行管理的嵌入,即您選擇的 LangChain Embeddings 物件。

如果您使用具有 Databricks 管理的嵌入的 delta-sync 索引

from databricks_langchain import DatabricksVectorSearch

vector_store = DatabricksVectorSearch(
endpoint=endpoint_name,
index_name=index_name,
)

如果您使用直接存取索引或具有自行管理的嵌入的 delta-sync 索引,您還需要提供嵌入模型和來源表中的文字欄位以用於嵌入

pip install -qU langchain-openai
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(model="text-embedding-3-large")
vector_store = DatabricksVectorSearch(
endpoint=endpoint_name,
index_name=index_name,
embedding=embeddings,
# The column name in the index that contains the text data to be embedded
text_column="document_content",
)

管理向量儲存 (Manage vector store)

將項目新增至向量儲存 (Add items to vector store)

注意:僅直接存取 (direct-access)索引支援透過 add_documents 方法將項目新增至向量儲存。

from langchain_core.documents import Document

document_1 = Document(page_content="foo", metadata={"source": "https://example.com"})

document_2 = Document(page_content="bar", metadata={"source": "https://example.com"})

document_3 = Document(page_content="baz", metadata={"source": "https://example.com"})

documents = [document_1, document_2, document_3]

vector_store.add_documents(documents=documents, ids=["1", "2", "3"])
API 參考:Document
['1', '2', '3']

從向量儲存中刪除項目 (Delete items from vector store)

注意:僅直接存取 (direct-access)索引支援透過 delete 方法刪除向量儲存中的項目。

vector_store.delete(ids=["3"])
True

查詢向量儲存 (Query vector store)

建立向量儲存並新增相關文件後,您很可能希望在鏈或代理程式執行期間查詢它。

直接查詢 (Query directly)

可以按如下方式執行簡單的相似度搜尋

results = vector_store.similarity_search(
query="thud", k=1, filter={"source": "https://example.com"}
)
for doc in results:
print(f"* {doc.page_content} [{doc.metadata}]")
* foo [{'id': '1'}]

注意:預設情況下,相似度搜尋只會傳回主索引鍵和文字欄位。如果您想檢索與文件相關聯的自訂中繼資料,請在初始化向量儲存時,在 columns 參數中傳遞其他欄位。

vector_store = DatabricksVectorSearch(
endpoint=endpoint_name,
index_name=index_name,
embedding=embeddings,
text_column="text",
columns=["source"],
)

results = vector_store.similarity_search(query="thud", k=1)
for doc in results:
print(f"* {doc.page_content} [{doc.metadata}]")
* foo [{'source': 'https://example.com', 'id': '1'}]

如果您想執行相似度搜尋並接收對應的分數,您可以執行

results = vector_store.similarity_search_with_score(
query="thud", k=1, filter={"source": "https://example.com"}
)
for doc, score in results:
print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")
* [SIM=0.414035] foo [{'source': 'https://example.com', 'id': '1'}]

透過轉換為檢索器來查詢 (Query by turning into retriever)

您也可以將向量儲存轉換為檢索器,以便在您的鏈中更輕鬆地使用。

retriever = vector_store.as_retriever(search_type="mmr", search_kwargs={"k": 1})
retriever.invoke("thud")
[Document(metadata={'source': 'https://example.com', 'id': '1'}, page_content='foo')]

用於檢索增強型生成 (Retrieval-Augmented Generation) 的使用方式 (Usage for retrieval-augmented generation)

有關如何使用此向量儲存進行檢索增強型生成 (RAG) 的指南,請參閱以下章節

API 參考文檔

如需所有 DatabricksVectorSearch 功能和設定的詳細文檔,請前往 API 參考文檔:https://langchain-python.dev.org.tw/api_reference/databricks/vectorstores/langchain_databricks.vectorstores.DatabricksVectorSearch.html


此頁面是否有幫助?