跳到主要內容

ClickHouse

ClickHouse 是最快速且資源效率最高的開源資料庫,適用於即時應用程式和分析,具有完整的 SQL 支援和廣泛的功能,可協助使用者編寫分析查詢。 最近新增的資料結構和距離搜尋功能(例如 L2Distance)以及 近似最近鄰搜尋索引 使 ClickHouse 能夠用作高性能且可擴展的向量資料庫,以使用 SQL 儲存和搜尋向量。

本筆記本示範如何使用與 ClickHouse 向量儲存相關的功能。

設定

首先使用 docker 設定本機 clickhouse 伺服器

! docker run -d -p 8123:8123 -p9000:9000 --name langchain-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server:23.4.2.11

您需要安裝 langchain-communityclickhouse-connect 才能使用此整合

pip install -qU langchain-community clickhouse-connect

憑證

此筆記本沒有憑證,只需確保您已按照上述說明安裝套件即可。

如果您想要獲得一流的自動化追蹤模型呼叫,您也可以取消註解以下內容來設定您的 LangSmith API 金鑰

# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"

例項化

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")
from langchain_community.vectorstores import Clickhouse, ClickhouseSettings

settings = ClickhouseSettings(table="clickhouse_example")
vector_store = Clickhouse(embeddings, config=settings)

管理向量儲存

建立向量儲存後,我們可以透過新增和刪除不同的項目與其互動。

將項目新增至向量儲存

我們可以使用 add_documents 函式將項目新增到向量儲存。

from uuid import uuid4

from langchain_core.documents import Document

document_1 = Document(
page_content="I had chocalate chip pancakes and scrambled eggs for breakfast this morning.",
metadata={"source": "tweet"},
)

document_2 = Document(
page_content="The weather forecast for tomorrow is cloudy and overcast, with a high of 62 degrees.",
metadata={"source": "news"},
)

document_3 = Document(
page_content="Building an exciting new project with LangChain - come check it out!",
metadata={"source": "tweet"},
)

document_4 = Document(
page_content="Robbers broke into the city bank and stole $1 million in cash.",
metadata={"source": "news"},
)

document_5 = Document(
page_content="Wow! That was an amazing movie. I can't wait to see it again.",
metadata={"source": "tweet"},
)

document_6 = Document(
page_content="Is the new iPhone worth the price? Read this review to find out.",
metadata={"source": "website"},
)

document_7 = Document(
page_content="The top 10 soccer players in the world right now.",
metadata={"source": "website"},
)

document_8 = Document(
page_content="LangGraph is the best framework for building stateful, agentic applications!",
metadata={"source": "tweet"},
)

document_9 = Document(
page_content="The stock market is down 500 points today due to fears of a recession.",
metadata={"source": "news"},
)

document_10 = Document(
page_content="I have a bad feeling I am going to get deleted :(",
metadata={"source": "tweet"},
)

documents = [
document_1,
document_2,
document_3,
document_4,
document_5,
document_6,
document_7,
document_8,
document_9,
document_10,
]
uuids = [str(uuid4()) for _ in range(len(documents))]

vector_store.add_documents(documents=documents, ids=uuids)
API 參考:Document

從向量儲存中刪除項目

我們可以透過 ID 使用 delete 函式從向量儲存中刪除項目。

vector_store.delete(ids=uuids[-1])

查詢向量儲存

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

直接查詢

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

results = vector_store.similarity_search(
"LangChain provides abstractions to make working with LLMs easy", k=2
)
for res in results:
print(f"* {res.page_content} [{res.metadata}]")

具有分數的相似度搜尋

您也可以使用分數進行搜尋

results = vector_store.similarity_search_with_score("Will it be hot tomorrow?", k=1)
for res, score in results:
print(f"* [SIM={score:3f}] {res.page_content} [{res.metadata}]")

篩選

您可以直接存取 ClickHouse SQL where 語句。 您可以按照標準 SQL 撰寫 WHERE 子句。

注意:請注意 SQL 注入,此介面不得由最終使用者直接呼叫。

如果您在設定下自訂 column_map,您可以像這樣使用篩選器進行搜尋

meta = vector_store.metadata_column
results = vector_store.similarity_search_with_relevance_scores(
"What did I eat for breakfast?",
k=4,
where_str=f"{meta}.source = 'tweet'",
)
for res in results:
print(f"* {res.page_content} [{res.metadata}]")

其他搜尋方法

本筆記本未涵蓋各種其他搜尋方法,例如 MMR 搜尋或按向量搜尋。 如需 Clickhouse 向量儲存可用的完整搜尋功能清單,請查看 API 參考

透過轉換為檢索器進行查詢

您也可以將向量儲存轉換成檢索器,以便在您的鏈中使用。

以下是如何將您的向量儲存轉換成檢索器,然後使用簡單的查詢和篩選來調用檢索器。

retriever = vector_store.as_retriever(
search_type="similarity_score_threshold",
search_kwargs={"k": 1, "score_threshold": 0.5},
)
retriever.invoke("Stealing from the bank is a crime", filter={"source": "news"})

用於檢索增強生成的使用方式

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

如需更多資訊,請查看使用 Astra DB 的完整 RAG 範本此處

API 參考

有關所有 Clickhouse 功能和配置的詳細文件,請前往 API 參考:https://langchain-python.dev.org.tw/api_reference/community/vectorstores/langchain_community.vectorstores.clickhouse.Clickhouse.html


此頁面是否有幫助?