要让内部笔记或工单变得可搜索,很容易就会走上针对每个使用场景分别构建搜索引擎的路。Chroma 是一个用于存储和搜索嵌入向量的轻量级数据库,也可以嵌入应用程序中。我安装了 Chroma,并在断开网络的情况下测试了语义搜索。
Chroma 会将文档转换为嵌入向量,保存这些向量,再按与查询的距离对结果排序后返回。Chroma 项目使用 Apache 2.0 License(*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 会将数据持久化为磁盘上的文件,因此对于小规模的笔记和 FAQ 搜索来说,这套方案已经足够。
来源
*1 Chroma (GitHub), https://github.com/chroma-core/chroma, Apache 2.0 License