スパースベクトルインデックス
スパースベクトルインデックス(SparseVectorIndexConfig)は、キーワードに基づく検索機能を強化することを目的としています。従来の密ベクトル(Dense Vector、例:BERT/OpenAI Embeddings)が意味のマッチングに重点を置くのとは対照的に、スパースベクトル(Sparse Vector、例:BM25, SPLADE)は正確なキーワードの一致に重点を置いています。
適用シナリオと利点
- 厳密なキーワードマッチング:固有名詞、略語、シリアル番号、または特定業界の専門用語について、疎ベクトルは密ベクトルよりも正確なマッチング結果を提供することが多いです。
- 解釈可能性が高い:疎ベクトルの各次元は通常、語彙表のトークンに対応しており、検索結果の解釈が容易です。
- 領域外一般化性能 (Out-of-Domain):特定の領域に対して密モデルを微調整しない場合、統計的手法に基づく疎モデル(BM25など)は通常、より堅牢な性能を発揮します。
- ハイブリッド検索 (Hybrid Search):密ベクトルの意味理解能力と疎ベクトルの厳密なマッチング能力を組み合わせることで、検索の再現率(Recall@K)を大幅に向上させることができます。
フィールド説明
SparseVectorIndexConfigは、BM25やSPLADEなどの疎ベクトルインデックスに使用され、密ベクトルとのハイブリッド検索をサポートします。関連するフィールドの説明は以下の通りです:
| フィールド | 型 | デフォルト値 | 説明と制約 | 必須 |
|---|---|---|---|---|
| embedding_function | SparseEmbeddingFunction | なし | 永続化(name、get_config、build_from_config)をサポートしている必要があります | はい |
| source_key | str | K | K.DOCUMENT | 疎ベクトルを生成するデータソースを指定します。データソース:#documentまたはmetadataフィールド名(例:"title") | いいえ |
| lib | str | "vsag" | 現在はvsagのみサポートしています | いいえ |
| distance | str | "inner_product" | 疎ベクトルはinner_productのみサポートしています | いいえ |
| type | str | "sindi" | 現在はsindiのみサポートしています | いいえ |
| prune | bool | False | クリップを有効にするかどうか | いいえ |
| refine | bool | False | refineを有効にするかどうか | いいえ |
| drop_ratio_build | float | 0.0 | インデックス構築時に小さな重みを無視する割合 (0.0 - 0.9) | いいえ |
| drop_ratio_search | float | 0.0 | 検索時に小さな重みを無視する割合 (0.0 - 0.9)。値が大きいほど検索は速くなりますが、精度が低下する可能性があります | いいえ |
| refine_k | float | 4.0 | 候補集合を再ソートする倍数 (1.0 - 1000.0) | いいえ |
| properties | dict | なし | キーと値は原始型である必要があります | いいえ |
制約と動作:
- 各コレクションでは最大1つの疎ベクトルインデックスを設定できます。疎ベクトルは
sparse_embedding列に書き込まれます。 source_keyがK.DOCUMENTまたは"#document"の場合、文書内容から生成されることを意味します。通常の文字列の場合はmetadata[source_key]から生成されることを意味します。resolve_source_key()は("document", None)または("metadata", metadata_key)を返し、内部または呼び出し元がデータソースを区別しやすくします。
使用方法
pyseekdbで疎ベクトルインデックスを使用するには、コレクション作成時にSchemaを通じて設定する必要があります。
前提条件
pyseekdb V1.2.0以降のバージョンがインストールされていることを確認してください。
pip install -U pyseekdb
BM25を使用する場合は、依存関係をインストールする必要があります。
pip install "bm25s[full]"
SPLADEを使用する場合は、依存関係をインストールする必要があります。
pip install sentence-transformers>=4.0
使用例
-
組み込みBM25アルゴリズムを使用した疎ベクトルインデックスの設定
import pyseekdb
from pyseekdb import Client, Schema, SparseVectorIndexConfig, K
from pyseekdb.utils.embedding_functions import BM25SparseEmbeddingFunction
# 1. クライアントの初期化(ここではEmbeddedモードを使用)
client = Client()
# 2. Schemaの定義
# BM25疎ベクトルインデックスを設定し、ドキュメントの内容(K.DOCUMENT)をソースとして使用する
sparse_config = SparseVectorIndexConfig(
embedding_function=BM25SparseEmbeddingFunction(k=1.2, b=0.75),
source_key=K.DOCUMENT, # "title"などのmetadataフィールドを指定することもできる
drop_ratio_search=0.2 # サーチ時の剪枝比率で、高速化に使用される
)
schema = Schema(
sparse_vector_index=sparse_config
)
# 3. コレクションの作成
collection_name = "demosparse_collection"
if collection_name in client.list_collections():
client.delete_collection(collection_name)
collection = client.create_collection(
name=collection_name,
schema=schema
)
# 4. データの追加
# pyseekdbは設定されたBM25関数を使用して自動的に疎ベクトルを生成します。
collection.add(
ids=["1", "2", "3"],
documents=[
"Machine learning is fascinating.",
"Python is a great programming language.",
"Artificial Intelligence and machine learning are related."
]
)
# 5. 疎ベクトル検索の実行
# query_key=K.SPARSE_EMBEDDING を使用して疎インデックスの使用を指定する
results = collection.query(
query_texts=["machine learning"],
query_key=K.SPARSE_EMBEDDING,
n_results=2
)
print("Sparse Search Results:", results) -
組み込みSPLADEアルゴリズムを使用した疎ベクトルインデックスの設定
深層学習モデル(例:SPLADE)で生成された疎ベクトルを使用したい場合は、
HuggingFaceSparseEmbeddingFunctionを使用できます。from pyseekdb.utils.embedding_functions import HuggingFaceSparseEmbeddingFunction
splade_ef = HuggingFaceSparseEmbeddingFunction(
device="cpu"
)
config = SparseVectorIndexConfig(embedding_function=splade_ef) -
密ベクトルと疎ベクトルのハイブリッド検索の例
ハイブリッド検索とは通常、密ベクトル検索(意味)と疎ベクトル検索(キーワード)を同時に実行し、その後アルゴリズム(加重平均やRRF逆ランキング融合など)を用いて結果を統合することを指します。
以下は、RERANKERモデル(cross-encoder/ms-marco-MiniLM-L-6-v2)を使用して結果を統合する完全なハイブリッド検索の実装例です。
-
依存環境(pyseekdbとsplade疎モデル)をインストールします。
pip install pyseekdb sentence-transformers -
密ベクトルと疎ベクトルのハイブリッド検索の例は以下の通りです。
# =====================================================================
# Hybrid search with pluggable reranking strategies
# まず依存関係をインストールします:
# pip install pyseekdb sentence-transformers
# =====================================================================
import pyseekdb
from pyseekdb import Client, Schema, SparseVectorIndexConfig, HNSWConfiguration, K
from pyseekdb.utils.embedding_functions import HuggingFaceSparseEmbeddingFunction
from typing import Any
def _rerank_model(
query_text: str,
candidate_ids: list[str],
candidate_docs: dict[str, str],
model_name: str,
) -> dict[str, float]:
"""
Cross-encoder reranking: score every (query, document) pair with a
cross-encoder model and return the relevance scores.
Requirements: ``pip install sentence-transformers``
"""
from sentence_transformers import CrossEncoder
model = CrossEncoder(model_name)
pairs = [(query_text, candidate_docs[doc_id]) for doc_id in candidate_ids]
raw_scores: list[float] = model.predict(pairs).tolist()
return dict(zip(candidate_ids, raw_scores, strict=True))
def perform_hybrid_search(
collection,
query_text: str,
top_k: int = 5,
*,
rrf_k: int = 60,
rerank_model: str = "cross-encoder/ms-marco-MiniLM-L-6-v2",
) -> dict[str, Any]:
"""
Hybrid search combining dense and sparse retrieval with pluggable reranking.
Args:
collection: pyseekdb collection (must have both dense and sparse indexes).
query_text: The query string.
top_k: Number of final results to return.
rerank_model: HuggingFace cross-encoder model name (only used when
``rerank="model"``).
Returns:
``{"ids": [...], "documents": [...], "scores": [...]}``
"""
# 1. 両方のインデックスから候補を取得する
dense_results = collection.query(query_texts=[query_text], n_results=top_k)
sparse_results = collection.query(
query_texts=[query_text],
query_key=K.SPARSE_EMBEDDING,
n_results=top_k,
)
dense_ids: list[str] = dense_results["ids"][0] if dense_results["ids"] else []
sparse_ids: list[str] = sparse_results["ids"][0] if sparse_results["ids"] else []
# 2. 再ランキング
all_ids = list(dict.fromkeys(dense_ids + sparse_ids))
if not all_ids:
return {"ids": [], "documents": [], "scores": []}
fetched = collection.get(ids=all_ids)
id_to_doc = dict(zip(fetched["ids"], fetched["documents"], strict=True))
scores = _rerank_model(query_text, all_ids, id_to_doc, rerank_model)
# 3. 得点降順に並べ替え、上位k件を取る
sorted_ids = sorted(scores, key=scores.get, reverse=True)[:top_k]
if not sorted_ids:
return {"ids": [], "documents": [], "scores": []}
# 4. 最終的な順序でドキュメントを取得する
fetched = collection.get(ids=sorted_ids)
id_to_doc = dict(zip(fetched["ids"], fetched["documents"], strict=True))
return {
"ids": sorted_ids,
"documents": [id_to_doc.get(sid, "") for sid in sorted_ids],
"scores": [round(scores[sid], 6) for sid in sorted_ids],
}
# =====================================================================
# Demo: hybrid search with all three reranking strategies
# =====================================================================
hybrid_collection_name = "hybrid_demo"
client = Client()
schema = Schema(
vector_index=HNSWConfiguration(dimension=384),
sparse_vector_index=SparseVectorIndexConfig(
embedding_function=HuggingFaceSparseEmbeddingFunction(),
source_key=K.DOCUMENT,
),
)
collection = client.create_collection(hybrid_collection_name, schema=schema)
docs = [
"Apple uses advanced chips in iPhones.",
"Apples are red and delicious fruits.",
"Oranges are rich in Vitamin C.",
"Apple pie is a popular dessert.",
"The tech giant Apple released a new laptop.",
]
ids = [str(i) for i in range(len(docs))]
collection.add(documents=docs, ids=ids)
query = "apple fruit"
# --- Cross-encoder reranker (requires sentence-transformers) ---
try:
print(f"\n=== Query: '{query}' | rerank='model' ===")
results = perform_hybrid_search(collection, query)
for i, doc_id in enumerate(results["ids"]):
print(f" {i + 1}. ID={doc_id} score={results['scores'][i]:.6f} | {results['documents'][i]}")
except ImportError:
print("\n(install sentence-transformers to enable: `pip install sentence-transformers)")
# 実行可能な出力結果:
# 1. ID=1 score=5.194160 | Apples are red and delicious fruits.
# 2. ID=3 score=-5.246192 | Apple pie is a popular dessert.
# 3. ID=4 score=-9.493382 | The tech giant Apple released a new laptop.
# 4. ID=0 score=-9.543316 | Apple uses advanced chips in iPhones.
# 5. ID=2 score=-10.001063 | Oranges are rich in Vitamin C.
-