← 研究ノート
検索エンジンではなく、ベクトルDBを置く。Chromaを動かす

検索エンジンではなく、ベクトルDBを置く。Chromaを動かす

埋め込みベクトルを保存・検索するデータベースChromaを、ネットワーク遮断のまま動かした記録。言い回しの異なる問い合わせでも、意味的に近いメモを正しく引き当てた。

この記事で取り扱うリポジトリ

chroma-core/chroma

Search infrastructure for AI

28.8k Rust Apache License 2.0

社内のメモやチケットを検索できるようにしたいとき、都度検索エンジンを構築するのは大掛かりに感じることがある。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. 言い回しの違うクエリで検索する

4件の短いメモを登録し、そのどれとも単語がほぼ重ならないクエリで検索した。ネットワークを遮断した状態で実行する。

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)は4件のメモのどの文とも完全には一致しないが、税務・請求関連の2件が正しく上位に来て、Wi-Fiやトマトの水やりに関するメモは除外された。ベクトルの近さだけで、意味の近い文書を選び分けている。

アプリケーションの中に、検索を持たせる

外部の検索サービスを構築・運用しなくても、アプリケーションの中に埋め込みベクトルの保存と検索を直接持たせられる。ディスク上のファイルとして永続化できるので、小規模なメモ検索やFAQ検索のような用途であれば、これだけで十分に機能する。

出典

*1 Chroma (GitHub), https://github.com/chroma-core/chroma, Apache 2.0 License