メインコンテンツまでスキップ
バージョン: V1.4.1

スパースベクトルインデックス

スパースベクトルインデックス(SparseVectorIndexConfig)は、キーワードに基づく検索機能を強化することを目的としています。従来の密ベクトル(Dense Vector、例:BERT/OpenAI Embeddings)が意味マッチングに重点を置くのに対し、スパースベクトル(Sparse Vector、例:BM25, SPLADE)はキーワードの厳密な一致に重点を置いています。

適用シナリオと利点​

  • 厳密なキーワードマッチング:固有名詞、略語、シリアル番号、または特定業界の専門用語について、疎ベクトルは密ベクトルよりも正確なマッチング結果を提供できることが多い。
  • 解釈可能性が高い:疎ベクトルの各次元は通常、単語表の1つのトークンに対応しており、検索結果がより解釈しやすい。
  • ドメイン外一般化性能 (Out-of-Domain):特定の領域に対して密モデルを微調整しない場合、統計的に基づく疎モデル(BM25など)は通常、より堅牢な性能を発揮する。
  • ハイブリッド検索 (Hybrid Search):密ベクトルの意味理解能力と疎ベクトルの厳密なマッチング能力を組み合わせることで、通常、検索の再現率(Recall@K)を大幅に向上させることができる。

フィールドの説明​

SparseVectorIndexConfigは、BM25やSPLADEなどの疎ベクトルインデックスに使用され、密ベクトルとのハイブリッド検索をサポートします。関連するフィールドの説明は以下のとおりです。

フィールド型デフォルト値説明と制約必須
embedding_functionSparseEmbeddingFunctionなし永続化をサポートする必要があります (name、get_config、build_from_config)。はい
source_keystr | KK.DOCUMENT疎ベクトルを生成するデータソースを指定します。データソース:#document または metadata フィールド名 (例:"title")いいえ
libstr"vsag"現在は vsag のみサポートしていますいいえ
distancestr"inner_product"疎ベクトルは inner_product のみサポートしていますいいえ
typestr"sindi"現在は sindi のみサポートしていますいいえ
pruneboolFalse剪枝を有効にするかどうかいいえ
refineboolFalserefine を有効にするかどうかいいえ
drop_ratio_buildfloat0.0インデックス構築時に小さな重みを無視する割合 (0.0 - 0.9)いいえ
drop_ratio_searchfloat0.0検索時に小さな重みを無視する割合 (0.0 - 0.9)。値が大きいほど検索は速くなりますが、精度が低下する可能性がありますいいえ
refine_kfloat4.0候補集合の再ソート倍率 (1.0 - 1000.0)いいえ
propertiesdictなしキーと値はプリミティブタイプである必要がありますいいえ

制約と動作:

  • 各コレクションでは、最大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の定義
    # ドキュメントの内容(K.DOCUMENT)をソースとして使用し、BM25の疎ベクトルインデックスを設定します。
    sparse_config = SparseVectorIndexConfig(
    embedding_function=BM25SparseEmbeddingFunction(k=1.2, b=0.75),
    source_key=K.DOCUMENT, # "title"などのメタデータフィールドを指定することもできます。
    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)を使用して結果を統合する完全なハイブリッド検索の実装例です。

    1. 依存環境(pyseekdbとspledeの疎モデル)のインストール。

      pip install pyseekdb sentence-transformers
    2. 密ベクトルと疎ベクトルのハイブリッド検索の例は以下のとおりです。

      # =====================================================================
      # Hybrid search with pluggable reranking strategies
      # Install denpendencies first:
      # 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.

      Requires: ``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.