mcpField
Q
qdrant-vector-search

qdrant-vector-search

github.com/orchestra-researchデータ・データベース14.1k977 回インストール19 週間前に更新
リポジトリ

qdrant-vector-search について

検索、レコメンデーション、RAGシステムを構築する開発者向けに、Rust製ベクトルデータベースQdrantを解説するガイドです。密ベクトルと疎ベクトル、メタデータフィルター、量子化、分散配置を扱います。

主な機能

  1. 01密・疎・マルチベクトルの保存
  2. 02メタデータで絞り込む類似検索
  3. 03ハイブリッド検索ワークフロー
  4. 04スカラー・積・バイナリ量子化
  5. 05シャーディングとレプリケーション
  6. 06RESTおよびgRPC API

活用シーン

  1. 01本番環境のRAG検索を構築
  2. 02メタデータでベクトル検索を絞り込み
  3. 03リアルタイム推薦システムを作成
  4. 04シャーディングでベクトルコレクションを拡張

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/orchestra-research/ai-research-skills --skill qdrant-vector-search

インストール後、Claude Code で/qdrant-vector-searchを入力して読み込まれたか確認します。

同梱ファイルreferences/advanced-usage.mdreferences/troubleshooting.md

詳細

Qdrant - ベクトル類似検索エンジン

本番環境の RAG やセマンティック検索向けに Rust で書かれた、高性能なベクトルデータベースです。

Qdrant を使うべき場面

Qdrant を使うべき場合:

  • 低レイテンシが求められる本番環境の RAG システムを構築する場合
  • ハイブリッド検索(ベクトル + メタデータフィルタリング)が必要な場合
  • シャーディングやレプリケーションによる水平スケーリングが必要な場合
  • 完全なデータ管理のためにオンプレミス展開を望む場合
  • レコードごとに複数のベクトル(デンス + スパース)を保存する必要がある場合
  • リアルタイムのレコメンデーションシステムを構築する場合

主な機能:

  • Rust 製: メモリ安全で高性能
  • 豊富なフィルタリング: 検索時に任意のペイロードフィールドでフィルタリング
  • 複数ベクトル: ポイントごとにデンス、スパース、マルチデンスをサポート
  • 量子化: メモリ効率のためのスカラー、プロダクト、バイナリ量子化
  • 分散処理: Raft コンセンサス、シャーディング、レプリケーション
  • REST + gRPC: 両方の API で機能が完全に同等

代わりに検討すべきもの:

  • Chroma: よりシンプルなセットアップ、組み込み用途向け
  • FAISS: 最大の生の速度が必要、研究用途やバッチ処理向け
  • Pinecone: フルマネージドで運用不要を優先する場合
  • Weaviate: GraphQL を好む場合、組み込みのベクトライザーが必要な場合

クイックスタート

インストール
# Python client
pip install qdrant-client

# Docker (recommended for development)
docker run -p 6333:6333 -p 6334:6334 qdrant/qdrant

# Docker with persistent storage
docker run -p 6333:6333 -p 6334:6334 \
    -v $(pwd)/qdrant_storage:/qdrant/storage \
    qdrant/qdrant
基本的な使い方
from qdrant_client import QdrantClient
from qdrant_client.models import Distance, VectorParams, PointStruct

# Connect to Qdrant
client = QdrantClient(host="localhost", port=6333)

# Create collection
client.create_collection(
    collection_name="documents",
    vectors_config=VectorParams(size=384, distance=Distance.COSINE)
)

# Insert vectors with payload
client.upsert(
    collection_name="documents",
    points=[
        PointStruct(
            id=1,
            vector=[0.1, 0.2, ...],  # 384-dim vector
            payload={"title": "Doc 1", "category": "tech"}
        ),
        PointStruct(
            id=2,
            vector=[0.3, 0.4, ...],
            payload={"title": "Doc 2", "category": "science"}
        )
    ]
)

# Search with filtering
results = client.search(
    collection_name="documents",
    query_vector=[0.15, 0.25, ...],
    query_filter={
        "must": [{"key": "category", "match": {"value": "tech"}}]
    },
    limit=10
)

for point in results:
    print(f"ID: {point.id}, Score: {point.score}, Payload: {point.payload}")

基本概念

ポイント - 基本データ単位
from qdrant_client.models import PointStruct

# Point = ID + Vector(s) + Payload
point = PointStruct(
    id=123,                              # Integer or UUID string
    vector=[0.1, 0.2, 0.3, ...],        # Dense vector
    payload={                            # Arbitrary JSON metadata
        "title": "Document title",
        "category": "tech",
        "timestamp": 1699900000,
        "tags": ["python", "ml"]
    }
)

# Batch upsert (recommended)
client.upsert(
    collection_name="documents",
    points=[point1, point2, point3],
    wait=True  # Wait for indexing
)
コレクション - ベクトルのコンテナ
from qdrant_client.models import VectorParams, Distance, HnswConfigDiff

# Create with HNSW configuration
client.create_collection(
    collection_name="documents",
    vectors_config=VectorParams(
        size=384,                        # Vector dimensions
        distance=Distance.COSINE         # COSINE, EUCLID, DOT, MANHATTAN
    ),
    hnsw_config=HnswConfigDiff(
        m=16,                            # Connections per node (default 16)
        ef_construct=100,                # Build-time accuracy (default 100)
        full_scan_threshold=10000        # Switch to brute force below this
    ),
    on_disk_payload=True                 # Store payload on disk
)

# Collection info
info = client.get_collection("documents")
print(f"Points: {info.points_count}, Vectors: {info.vectors_count}")
距離メトリック
メトリック用途範囲
COSINEテキスト埋め込み、正規化されたベクトル0 〜 2
EUCLID空間データ、画像特徴量0 〜 ∞
DOTレコメンデーション、非正規化データ-∞ 〜 ∞
MANHATTANスパース特徴量、離散データ0 〜 ∞

検索操作

基本検索
# Simple nearest neighbor search
results = client.search(
    collection_name="documents",
    query_vector=[0.1, 0.2, ...],
    limit=10,
    with_payload=True,
    with_vectors=False  # Don't return vectors (faster)
)
フィルタ付き検索
from qdrant_client.models import Filter, FieldCondition, MatchValue, Range

# Complex filtering
results = client.search(
    collection_name="documents",
    query_vector=query_embedding,
    query_filter=Filter(
        must=[
            FieldCondition(key="category", match=MatchValue(value="tech")),
            FieldCondition(key="timestamp", range=Range(gte=1699000000))
        ],
        must_not=[
            FieldCondition(key="status", match=MatchValue(value="archived"))
        ]
    ),
    limit=10
)

# Shorthand filter syntax
results = client.search(
    collection_name="documents",
    query_vector=query_embedding,
    query_filter={
        "must": [
            {"key": "category", "match": {"value": "tech"}},
            {"key": "price", "range": {"gte": 10, "lte": 100}}
        ]
    },
    limit=10
)
バッチ検索
from qdrant_client.models import SearchRequest

# Multiple queries in one request
results = client.search_batch(
    collection_name="documents",
    requests=[
        SearchRequest(vector=[0.1, ...], limit=5),
        SearchRequest(vector=[0.2, ...], limit=5, filter={"must": [...]}),
        SearchRequest(vector=[0.3, ...], limit=10)
    ]
)

RAG との統合

sentence-transformers を使う場合
from sentence_transformers import SentenceTransformer
from qdrant_client import QdrantClient
from qdrant_client.models import VectorParams, Distance, PointStruct

# Initialize
encoder = SentenceTransformer("all-MiniLM-L6-v2")
client = QdrantClient(host="localhost", port=6333)

# Create collection
client.create_collection(
    collection_name="knowledge_base",
    vectors_config=VectorParams(size=384, distance=Distance.COSINE)
)

# Index documents
documents = [
    {"id": 1, "text": "Python is a programming language", "source": "wiki"},
    {"id": 2, "text": "Machine learning uses algorithms", "source": "textbook"},
]

points = [
    PointStruct(
        id=doc["id"],
        vector=encoder.encode(doc["text"]).tolist(),
        payload={"text": doc["text"], "source": doc["source"]}
    )
    for doc in documents
]
client.upsert(collection_name="knowledge_base", points=points)

# RAG retrieval
def retrieve(query: str, top_k: int = 5) -> list[dict]:
    query_vector = encoder.encode(query).tolist()
    results = client.search(
        collection_name="knowledge_base",
        query_vector=query_vector,
        limit=top_k
    )
    return [{"text": r.payload["text"], "score": r.score} for r in results]

# Use in RAG pipeline
context = retrieve("What is Python?")
prompt = f"Context: {context}\n\nQuestion: What is Python?"
LangChain を使う場合
from langchain_community.vectorstores import Qdrant
from langchain_community.embeddings import HuggingFaceEmbeddings

embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
vectorstore = Qdrant.from_documents(documents, embeddings, url="http://localhost:6333", collection_name="docs")
retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
LlamaIndex を使う場合
from llama_index.vector_stores.qdrant import QdrantVectorStore
from llama_index.core import VectorStoreIndex, StorageContext

vector_store = QdrantVectorStore(client=client, collection_name="llama_docs")
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)
query_engine = index.as_query_engine()

マルチベクトルのサポート

名前付きベクトル(異なる埋め込みモデル)
from qdrant_client.models import VectorParams, Distance

# Collection with multiple vector types
client.create_collection(
    collection_name="hybrid_search",
    vectors_config={
        "dense": VectorParams(size=384, distance=Distance.COSINE),
        "sparse": VectorParams(size=30000, distance=Distance.DOT)
    }
)

# Insert with named vectors
client.upsert(
    collection_name="hybrid_search",
    points=[
        PointStruct(
            id=1,
            vector={
                "dense": dense_embedding,
                "sparse": sparse_embedding
            },
            payload={"text": "document text"}
        )
    ]
)

# Search specific vector
results = client.search(
    collection_name="hybrid_search",
    query_vector=("dense", query_dense),  # Specify which vector
    limit=10
)
スパースベクトル(BM25、SPLADE)
from qdrant_client.models import SparseVectorParams, SparseIndexParams, SparseVector

# Collection with sparse vectors
client.create_collection(
    collection_name="sparse_search",
    vectors_config={},
    sparse_vectors_config={"text": SparseVectorParams(index=SparseIndexParams(on_disk=False))}
)

# Insert sparse vector
client.upsert(
    collection_name="sparse_search",
    points=[PointStruct(id=1, vector={"text": SparseVector(indices=[1, 5, 100], values=[0.5, 0.8, 0.2])}, payload={"text": "document"})]
)

量子化(メモリ最適化)

from qdrant_client.models import ScalarQuantization, ScalarQuantizationConfig, ScalarType

# Scalar quantization (4x memory reduction)
client.create_collection(
    collection_name="quantized",
    vectors_config=VectorParams(size=384, distance=Distance.COSINE),
    quantization_config=ScalarQuantization(
        scalar=ScalarQuantizationConfig(
            type=ScalarType.INT8,
            quantile=0.99,        # Clip outliers
            always_ram=True      # Keep quantized in RAM
        )
    )
)

# Search with rescoring
results = client.search(
    collection_name="quantized",
    query_vector=query,
    search_params={"quantization": {"rescore": True}},  # Rescore top results
    limit=10
)

ペイロードのインデックス作成

from qdrant_client.models import PayloadSchemaType

# Create payload index for faster filtering
client.create_payload_index(
    collection_name="documents",
    field_name="category",
    field_schema=PayloadSchemaType.KEYWORD
)

client.create_payload_index(
    collection_name="documents",
    field_name="timestamp",
    field_schema=PayloadSchemaType.INTEGER
)

# Index types: KEYWORD, INTEGER, FLOAT, GEO, TEXT (full-text), BOOL

本番環境への展開

Qdrant Cloud
from qdrant_client import QdrantClient

# Connect to Qdrant Cloud
client = QdrantClient(
    url="https://your-cluster.cloud.qdrant.io",
    api_key="your-api-key"
)
パフォーマンスチューニング
# Optimize for search speed (higher recall)
client.update_collection(
    collection_name="documents",
    hnsw_config=HnswConfigDiff(ef_construct=200, m=32)
)

# Optimize for indexing speed (bulk loads)
client.update_collection(
    collection_name="documents",
    optimizer_config={"indexing_threshold": 20000}
)

ベストプラクティス

  1. バッチ処理 - 効率のためにバッチの upsert / 検索を使用する
  2. ペイロードのインデックス作成 - フィルタで使用するフィールドにインデックスを付ける
  3. 量子化 - 大規模なコレクション(>1M ベクトル)で有効にする
  4. シャーディング - >10M ベクトルのコレクションで使用する
  5. ディスク上のストレージ - 大きなペイロードには on_disk_payload を有効にする
  6. コネクションプーリング - クライアントインスタンスを再利用する

よくある問題

フィルタ付き検索が遅い:

# Create payload index for filtered fields
client.create_payload_index(
    collection_name="docs",
    field_name="category",
    field_schema=PayloadSchemaType.KEYWORD
)

メモリ不足:

# Enable quantization and on-disk storage
client.create_collection(
    collection_name="large_collection",
    vectors_config=VectorParams(size=384, distance=Distance.COSINE),
    quantization_config=ScalarQuantization(...),
    on_disk_payload=True
)

接続の問題:

# Use timeout and retry
client = QdrantClient(
    host="localhost",
    port=6333,
    timeout=30,
    prefer_grpc=True  # gRPC for better performance
)

参考資料

  • Advanced Usage - 分散モード、ハイブリッド検索、レコメンデーション
  • Troubleshooting - よくある問題、デバッグ、パフォーマンスチューニング

リソース

コメント