Self-Hosted Vector Databases with Qdrant: A Deep Dive
Introduction
📖 Connexe à la série RAGM SK1 Cet article fournit une étude approfondie de Qdrant,, la base de données vectorielle utilisée dans:.
- Partie 4: ONNX & Mise en œuvre du Qdrant - Recherche sémantique du bâtiment
- Pièce 5: Recherche hybride & AutoM SK2Indexage - Intégration de la production
Qdrant Cet article traite des concepts fondamentaux de ,, du client C, des modèles de production et de l’ajustement de la performance.
Qu'est-ce que Qdrant?
A Base de données des vecteurs stocke des vecteurs dimensionnels élevés-Vektors dimensionnelles M SK1Insertions) et permet une recherche rapide de similitudesMSC3 Contrairement aux bases de données traditionnelles qui trouvent des matchs exacts , Les résultats Qdrant caractéristiques sémantiques similaires Articles.
flowchart LR
A[Text: 'Docker deployment'] --> B[Embedding Model]
B --> C["Vector: [0.12, -0.34, 0.56, ...]"]
C --> D[Qdrant]
E[Query: 'container setup'] --> F[Embedding Model]
F --> G["Vector: [0.11, -0.32, 0.58, ...]"]
G --> H[Similarity Search]
D --> H
H --> I[Similar Results]
style B stroke:#6366f1,stroke-width:3px
style D stroke:#ef4444,stroke-width:3px
style F stroke:#6366f1,stroke-width:3px
style H stroke:#10b981,stroke-width:2px
Principales caractéristiques de Qdrant:
- L'indexation du HNSW - Sous--temps de recherche linéaires
- Filtration - Combiner la recherche de similitude avec les filtres métadonnées
- gRPC & APIs REST - Accès de performance élevé
- Déploiement réparti - Élargir horizontalement
- Photos - sauvegarder et restaurer
Concepts fondamentaux
Collections
A collecte est comme une table - elle contient des vecteurs de dimensions fixes et d’une distance métrique
flowchart TB
subgraph Collection["Collection: blog_posts"]
A[Vector Size: 384]
B[Distance: Cosine]
C[HNSW Index]
end
subgraph Points
D[Point 1: slug=docker-intro]
E[Point 2: slug=kubernetes-basics]
F[Point N...]
end
Collection --> Points
style A stroke:#6366f1,stroke-width:2px
style B stroke:#6366f1,stroke-width:2px
style C stroke:#f59e0b,stroke-width:2px
style D stroke:#10b981,stroke-width:2px
style E stroke:#10b981,stroke-width:2px
// Create collection - see https://qdrant.tech/documentation/concepts/collections/#create-a-collection
await client.CreateCollectionAsync(
collectionName: "blog_posts",
vectorsConfig: new VectorParams
{
Size = 384, // Must match your embedding model
Distance = Distance.Cosine // Best for text embeddings
}
);
Mesures de la distance (Documents):
- Cosine - Mesure de l'angle entre les vecteurs le meilleur pour le texteM SK2
- Point - Produit intérieur brut (pour les vecteurs normalisés pré--)
- Euclid - Distance géométrique pour les données spatialesM SK2
Points
A point de vue est un seul dossier contenant:
flowchart LR
subgraph Point
A[ID: uuid/int]
B["Vector: float[384]"]
C[Payload: JSON metadata]
end
style A stroke:#8b5cf6,stroke-width:2px
style B stroke:#f59e0b,stroke-width:2px
style C stroke:#10b981,stroke-width:2px
// Upsert points - see https://qdrant.tech/documentation/concepts/points/#upload-points
var point = new PointStruct
{
Id = new PointId { Uuid = Guid.NewGuid().ToString() },
Vectors = embedding, // float[384]
Payload =
{
["slug"] = "my-post",
["title"] = "Vector Databases",
["language"] = "en",
["categories"] = new[] { "AI", "Databases" },
["published"] = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
}
};
await client.UpsertAsync("blog_posts", points: new[] { point });
Filtration
Filtration exécutions précédemment recherche de similitude - extrêmement efficace.
flowchart TB
A[Search Query] --> B{Apply Filters First}
B --> C[Language = 'en']
B --> D[Year >= 2024]
C --> E[Filtered Subset]
D --> E
E --> F[Vector Similarity Search]
F --> G[Ranked Results]
style B stroke:#ec4899,stroke-width:3px
style E stroke:#f59e0b,stroke-width:2px
style F stroke:#6366f1,stroke-width:2px
style G stroke:#10b981,stroke-width:2px
// Filter conditions - see https://qdrant.tech/documentation/concepts/filtering/#filtering-conditions
var filter = new Filter
{
Must = // AND conditions
{
new Condition { Field = new FieldCondition
{
Key = "language",
Match = new Match { Keyword = "en" }
}},
new Condition { Field = new FieldCondition
{
Key = "published",
Range = new Range { Gte = 1704067200 } // 2024-01-01
}}
},
MustNot = // Exclude conditions
{
new Condition { Field = new FieldCondition
{
Key = "slug",
Match = new Match { Keyword = "draft-post" }
}}
}
};
Types de filtre (Documents):
Match.Keyword- Correspondance exacte des chaînesMatch.Text- Correspondance complète-texteMatch.Any- Correspond à n'importe quel tableauRange- Étendues numériquesGeoBoundingBox/GeoRadius- Filtration géologique
Le client C#
Installer le document officiel Qdrant.Client paquet (GitHub):
dotnet add package Qdrant.Client
Établissement de la connexion
using Qdrant.Client;
using Qdrant.Client.Grpc;
// gRPC client (recommended) - see https://qdrant.tech/documentation/interfaces/#grpc-interface
var client = new QdrantClient(
host: "localhost",
port: 6334, // gRPC port (6333 is REST)
https: false
);
// With API key - see https://qdrant.tech/documentation/guides/security/
var secureClient = new QdrantClient(
host: "your-qdrant.cloud",
port: 6334,
https: true,
apiKey: "your-api-key"
);
Utiliser toujours gRPC (port 6334) pour la production - S3-5x plus rapide que REST
Windows HTTP/2 Fix
Sur Windows, activer HTTP non encrypté/2 précédemment Création du client:
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
Opérations clés
Rechercher
// Vector search - see https://qdrant.tech/documentation/concepts/search/
var results = await client.SearchAsync(
collectionName: "blog_posts",
vector: queryEmbedding,
limit: 10,
filter: filter,
scoreThreshold: 0.5f, // Minimum similarity
searchParams: new SearchParams
{
HnswEf = 128, // Search accuracy (higher = better recall)
Exact = false // Use approximate search
},
withPayload: true
);
foreach (var result in results)
{
Console.WriteLine($"{result.Payload["title"].StringValue}: {result.Score}");
}
Insérer les lots
// Batch operations - see https://qdrant.tech/documentation/concepts/points/#batch-update
var points = documents.Select(doc => new PointStruct
{
Id = new PointId { Uuid = doc.Id },
Vectors = doc.Embedding,
Payload = { ["slug"] = doc.Slug, ["title"] = doc.Title }
}).ToList();
await client.UpsertAsync(
collectionName: "blog_posts",
points: points,
wait: true // Wait for indexing
);
Supprimer
// Delete by filter - see https://qdrant.tech/documentation/concepts/points/#delete-points
await client.DeleteAsync(
collectionName: "blog_posts",
filter: new Filter
{
Must = { new Condition { Field = new FieldCondition
{
Key = "slug",
Match = new Match { Keyword = "old-post" }
}}}
}
);
Étalonnage de l'indice HNSW
HNSW (Hierarchical Navigable Small World ) est QdrantM SK2s index algorithme.
flowchart TB
subgraph "HNSW Graph Layers"
L2[Layer 2 - Sparse]
L1[Layer 1 - Medium]
L0[Layer 0 - Dense]
end
Q[Query] --> L2
L2 --> L1
L1 --> L0
L0 --> R[Nearest Neighbors]
style L2 stroke:#8b5cf6,stroke-width:2px
style L1 stroke:#6366f1,stroke-width:2px
style L0 stroke:#3b82f6,stroke-width:2px
style Q stroke:#10b981,stroke-width:2px
style R stroke:#ef4444,stroke-width:2px
Paramètres de l'index
// HNSW config - see https://qdrant.tech/documentation/concepts/indexing/#hnsw-index
var hnswConfig = new HnswConfigDiff
{
M = 16, // Edges per node (16-32 recommended)
EfConstruct = 100, // Build-time accuracy (100-200)
FullScanThreshold = 10000 // Brute force threshold
};
await client.UpdateCollectionAsync(
collectionName: "blog_posts",
hnswConfig: hnswConfig
);
Recherche-exactitude du temps:
var searchParams = new SearchParams
{
HnswEf = 128 // Higher = better recall, slower (64-256)
};
Lignes directrices pour l'alignement:
| Case d'utilisation | M | EfConstruct | HnswEf S | |||
|---|---|---|---|---|---|---|
| RapideM SK1 faible récupération | ||||||
| Équilibré | 16 | 3 | 4 | 5 | 6 | |
| Récupération élevée |
Indices de la charge de travail
Créer Les indices de la charge de travail pour les champs fréquemment filtrés:
// Keyword index - see https://qdrant.tech/documentation/concepts/indexing/#payload-index
await client.CreatePayloadIndexAsync(
collectionName: "blog_posts",
fieldName: "language",
schemaType: PayloadSchemaType.Keyword
);
// Integer index for ranges
await client.CreatePayloadIndexAsync(
collectionName: "blog_posts",
fieldName: "published",
schemaType: PayloadSchemaType.Integer
);
Répercussions 10-100x filtration plus rapide sur les grandes collectionsM SK1
Quantisation
Quantisation réduit l'utilisation de la mémoire:
// Scalar quantization - see https://qdrant.tech/documentation/guides/quantization/#scalar-quantization
await client.UpdateCollectionAsync(
collectionName: "blog_posts",
quantizationConfig: new ScalarQuantization
{
Scalar = new ScalarQuantizationConfig
{
Type = ScalarType.Int8, // float32 -> int8
Quantile = 0.99f,
AlwaysRam = true
}
}
);
Commerce-off 4x mémoire réduite, ~2% perte de rappelM SK3 |
Déploiement du docker
# docker-compose.yml - see https://qdrant.tech/documentation/guides/installation/
services:
qdrant:
image: qdrant/qdrant:v1.12.1 # Pin version!
ports:
- "6333:6333" # REST
- "6334:6334" # gRPC
volumes:
- qdrant_data:/qdrant/storage
environment:
- QDRANT__SERVICE__GRPC_PORT=6334
- QDRANT__SERVICE__HTTP_PORT=6333
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:6333/health"]
interval: 30s
timeout: 10s
retries: 3
volumes:
qdrant_data:
Sécurité
Activer Authentication de la clé API:
environment:
- QDRANT__SERVICE__API_KEY=your-secret-key
Surveillance
Metriques
Qdrant expose Mesures de Prometheus À l'heure actuelle /metrics:
curl http://localhost:6333/metrics
Mesures clés:
qdrant_collections_vector_count- Vektors totauxqdrant_rest_responses_duration_seconds- La latence de la demandeqdrant_memory_usage_bytes- Consommation de mémoire
Photos
Créer les sauvegardes:
# Create snapshot
curl -X POST http://localhost:6333/collections/blog_posts/snapshots
# List snapshots
curl http://localhost:6333/collections/blog_posts/snapshots
# Restore (copy snapshot to storage/collections/blog_posts/snapshots/)
Gotchas communs
1. Confusion des ports
- 6333 = REST API
- 6334 = API gRPC (utiliser ce !)
2. Ne pas correspondre aux dimensions du vecteur
Error: expected dim: 384, got 768
Votre modèle d'implantation et votre collection doivent correspondre:
all-MiniLM-L6-v2: 384 dimensionsnomic-embed-text: 768 dimensions- OpenAI
text-embedding-3-small: 1536 dimensions
3. Première demande lente
HNSW lazy-loads into memoryM SK1 Warm up after startup:
await client.SearchAsync("blog_posts", new float[384], limit: 1);
Filtration de l'Arraye 4.
Utilisation Match.Any pour les champs de tableaux:
new Match { Any = new RepeatedStrings { Strings = { "AI", "ML" } } }
Ressources
Documentation officielle de Qdrant
- Vue d'ensemble - Début
- Concepts - Concepts de base
- Collections - Création et gestion de collections
- Points - Travailler avec les vecteurs
- Rechercher - Opérations de recherche
- Filtration - Conditions de filtrage
- Indexage - HNSW et indices de charge de travail
- Quantisation - Optimisation de la mémoire
- Sécurité - Authentication
- Surveillance - Métrique et télémétrie
- Photos - sauvegarder et restaurer
Bibliothèques des clients
- Client Qdrant .NET - Officiel CM SK1 SDK
- NuGet Package - Dernière mise à jour
Articles connexes
- Partie 4: ONNX & Mise en œuvre du Qdrant
- Pièce 5: Recherche hybride & AutoM SK2Indexage
- Aperçu de la série RAG
Code de source
Tous les codes disponibles à: github.comM SK1scottgal/mostlylucidweb
Mostlylucid.SemanticSearch/Services/QdrantVectorStoreService.cs- Intégration de Qdrant