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-community
和 clickhouse-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)
從向量儲存刪除項目
我們可以使用 delete
函數依 ID 從向量儲存中刪除項目。
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