搜索内部文档或支持记录时,如果用词不同,关键词搜索就可能漏掉结果。即使某个段落回答的是同一个问题,只要措辞不同,也可能搜不到。人可以看出两段话虽然用词不同、表达的意思却相同,但简单的字符串匹配无法识别这种差异。txtai 是一个嵌入数据库,会把文本转换为语义向量并据此进行搜索。我安装了它,并测试它能否在查询与结果没有任何共同词语的情况下找到匹配内容。
txtai 是一个一体化框架,用于构建基于嵌入的搜索和 LLM 工作流。该项目以 Apache 2.0 许可证发布源代码(*1)。
1. 安装
在启用网络访问的构建阶段获取嵌入模型(sentence-transformers/all-MiniLM-L6-v2)。
FROM docker.io/library/python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'txtai==9.11.0'
COPY install_model.py /tmp/install_model.py
RUN python /tmp/install_model.py
WORKDIR /work
# install_model.py
import txtai
embeddings = txtai.Embeddings(path="sentence-transformers/all-MiniLM-L6-v2")
embeddings.index([(0, "warm up the model cache", None)])
print("warmup ok")
podman build -t txtai-sandbox .
2. 测试没有共同词语的搜索
我先索引了五个短句,然后使用一个与这些句子都没有共同词语的查询进行搜索。运行测试时,我断开了网络连接。
import txtai
embeddings = txtai.Embeddings(path="sentence-transformers/all-MiniLM-L6-v2")
documents = [
(0, "The cat sat quietly on the windowsill in the sun.", None),
(1, "Stock markets fell sharply after the interest rate announcement.", None),
(2, "A kitten curled up and slept on the warm windowsill.", None),
(3, "The central bank raised rates to fight inflation.", None),
(4, "She baked a loaf of sourdough bread this morning.", None),
]
embeddings.index(documents)
query = "a small cat napping by a window"
results = embeddings.search(query, 3)
for uid, score in results:
print(f"score={score:.3f} {documents[uid][1]}")
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 \
-v "$(pwd)":/work -w /work txtai-sandbox \
python search_demo.py
-v 选项会让容器能够读写指定目录。请在专门准备的空目录中运行此实验,不要把私钥或凭据放在那里。
命令返回了以下结果:
QUERY: a small cat napping by a window
score=0.638 A kitten curled up and slept on the warm windowsill.
score=0.612 The cat sat quietly on the windowsill in the sun.
score=0.243 She baked a loaf of sourdough bread this morning.
查询中的 napping 没有出现在前面两句话中的任何一句里。查询中的 small 也没有与 kitten 这个词匹配。两句关于猫的句子排在前两位,而不相关的面包句子得分低得多。两句关于加息和股价的金融句子没有进入前 3 名。txtai 仅凭语义相似度(字符串匹配数为零)重新排列了结果。
不使用匹配的关键词措辞进行搜索
你不必使用与已索引文本相同的词语。嵌入搜索允许你使用自己的表达方式。系统会处理不同的措辞,并返回含义接近的内容。这样,你就不用在搜索框前反复猜测哪些词能搜到结果。
来源
*1 txtai (GitHub), https://github.com/neuml/txtai, Apache 2.0 License