為內部筆記或工單加入搜尋功能時,可能會需要為每個使用情境建立搜尋引擎。Chroma 是一個輕量的資料庫,專為儲存及搜尋嵌入向量而設計,可以嵌入應用程式中。我安裝了 Chroma,並在網路斷線的情況下測試語意搜尋。
Chroma 將文件轉換為嵌入向量並儲存,接著依照與查詢的距離排序並回傳結果。Chroma 專案採用 Apache 2.0 授權條款 (*1)。
1. 安裝
在建置期間網路可用時,下載預設的 ONNX 嵌入模型。
FROM docker.io/library/python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'chromadb==1.5.9'
COPY warmup_model.py /tmp/warmup_model.py
RUN python /tmp/warmup_model.py
WORKDIR /work
# warmup_model.py
import chromadb
client = chromadb.Client()
collection = client.create_collection("warmup")
collection.add(documents=["warm up"], ids=["1"])
print("warmup ok")
podman build -t chromadb-sandbox .
2. 使用不同措辭的查詢進行搜尋
我登錄了四則簡短的筆記,並使用一個與這些筆記幾乎沒有共同字詞的查詢進行搜尋。請在網路斷線的情況下執行指令。
import chromadb
client = chromadb.PersistentClient(path="/work/chroma_db")
collection = client.get_or_create_collection("notes")
collection.add(
documents=[
"The invoice was rejected because the tax ID field was empty.",
"Restart the router if the wifi light stays orange for more than a minute.",
"The payment failed validation due to a missing tax identifier.",
"Water the tomato plants every morning before the sun gets strong.",
],
ids=["doc1", "doc2", "doc3", "doc4"],
)
query = "billing rejected, tax number missing"
results = collection.query(query_texts=[query], n_results=2)
for doc, dist in zip(results["documents"][0], results["distances"][0]):
print(f"distance={dist:.4f} {doc}")
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 \
-v "$(pwd)":/work -w /work chromadb-sandbox \
python search_demo.py
-v 選項讓容器能夠讀寫指定的目錄。請使用空目錄進行這項實驗。PersistentClient 會將資料以檔案形式保存在磁碟上,因此請勿將包含真實資料的現有資料庫檔案放在掛載點中。
指令產生了以下輸出。
QUERY: billing rejected, tax number missing
distance=0.6248 The payment failed validation due to a missing tax identifier.
distance=0.6592 The invoice was rejected because the tax ID field was empty.
查詢中的字詞 (billing, rejected, tax, number, missing) 與四則筆記中的任何句子都不完全相符。兩則關於稅務與帳款的筆記排名最高,Chroma 則排除了關於 Wi-Fi 和澆灌番茄的筆記。Chroma 僅依向量距離排列文件,意思相關的兩則筆記排在最前面。
將搜尋功能放入應用程式
您可以在應用程式內儲存及搜尋嵌入向量,不必建立或維運外部搜尋服務。Chroma 會將資料以檔案形式保存在磁碟上,因此這樣的設定足以應付小規模的筆記與常見問題搜尋。
來源
*1 Chroma (GitHub), https://github.com/chroma-core/chroma, Apache 2.0 License