# Bases de datos Vectores Auto-Hosted con Qdrant: Un Buceo Profundo

<datetime class="hidden">2025-11-23T13:00</datetime>

<!-- category -- ASP.NET, Semantic Search, Vector Databases, Qdrant, RAG, AI-Article -->
# Introducción

**Relacionado con la serie RAG:** Este artículo proporciona una inmersión profunda en Qdrant, la base de datos de vectores utilizada en:

- [Parte 4: Aplicación de ONNX & Qdrant](/blog/semantic-search-with-onnx-and-qdrant) - Construcción de búsqueda semántica
- [Parte 5: Búsqueda híbrida y auto-indexación](/blog/rag-hybrid-search-and-indexing) - Integración de la producción

[Qdrant](https://qdrant.tech/) (pronunciado "quadrant") es una base de datos de vectores de código abierto construida en Rust. Este artículo cubre conceptos básicos, el cliente C#, ajuste de rendimiento y patrones de producción.

[TOC]

# ¿Qué es Qdrant?

A [base de datos de vectores](https://qdrant.tech/documentation/overview/) almacena vectores de alta dimensión (embeddings) y permite la búsqueda rápida de similitud. A diferencia de las bases de datos tradicionales que encuentran coincidencias exactas, Qdrant encuentra *Semánticamente similar* items.

```mermaid
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
```

**Características clave de Qdrant:**

- [Indización de HNSW](https://qdrant.tech/documentation/concepts/indexing/) - Tiempos de búsqueda sublineales
- [Filtrado](https://qdrant.tech/documentation/concepts/filtering/) - Combinar búsqueda de similitud con filtros de metadatos
- [API de gRPC y REST](https://qdrant.tech/documentation/interfaces/) - Acceso de alto rendimiento
- [Despliegue distribuido](https://qdrant.tech/documentation/guides/distributed_deployment/) - Escalar horizontalmente
- [Snapshots](https://qdrant.tech/documentation/concepts/snapshots/) - Copia de seguridad y restaurar

# Conceptos básicos

## Recaudación

A [recogida](https://qdrant.tech/documentation/concepts/collections/) es como una tabla - tiene vectores con una dimensión fija y métrica de distancia.

```mermaid
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
```

```csharp
// 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
    }
);
```

**métricas de distancia** ([docs](https://qdrant.tech/documentation/concepts/collections/#distance-metrics)):

- **Cosina** - Mide el ángulo entre vectores (mejor para texto)
- **Punto** - Producto interior bruto (para vectores prenormalizados)
- **Euclides** - Distancia geométrica (para datos espaciales)

## Puntos

A [punto](https://qdrant.tech/documentation/concepts/points/) es un registro único que contiene:

```mermaid
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
```

```csharp
// 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 });
```

## Filtrado

[Filtrado](https://qdrant.tech/documentation/concepts/filtering/) corre *antes* búsqueda de similitud - extremadamente eficiente.

```mermaid
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
```

```csharp
// 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" }
        }}
    }
};
```

**Tipos de filtros** ([docs](https://qdrant.tech/documentation/concepts/filtering/#match)):

- `Match.Keyword` - Coincidencia de cadena exacta
- `Match.Text` - Coincidencia de texto completo
- `Match.Any` - Coincide con cualquier array
- `Range` - Alcances numéricos (Gte, Lte, Gt, Lt)
- `GeoBoundingBox` / `GeoRadius` - Filtrado geográfico

# El cliente C#

Instalar el oficial [Qdrant.Client](https://www.nuget.org/packages/Qdrant.Client) envase ([GitHub](https://github.com/qdrant/qdrant-dotnet)):

```bash
dotnet add package Qdrant.Client
```

## Configuración de la conexión

```csharp
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"
);
```

> **Usar siempre gRPC** (puerto 6334) para la producción - 3-5x más rápido que REST.

## Windows HTTP/2 Fix

En Windows, active HTTP/2 sin cifrar **antes** creación del cliente:

```csharp
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
```

## Operaciones clave

### Buscar

```csharp
// 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}");
}
```

### Lote upsert

```csharp
// 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
);
```

### Eliminar

```csharp
// 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" }
        }}}
    }
);
```

# Sintonización del índice HNSW

[HNSW](https://qdrant.tech/documentation/concepts/indexing/#vector-index) (Hierarchical Navigable Small World) es el algoritmo de índice de Qdrant.

```mermaid
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
```

## Parámetros del índice

```csharp
// 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
);
```

**Precisión del tiempo de búsqueda:**

```csharp
var searchParams = new SearchParams
{
    HnswEf = 128  // Higher = better recall, slower (64-256)
};
```

**Directrices de puesta a punto:**
Asunto de utilización  M  EfConstruct  HnswEf
|----------|---|-------------|--------|
# Rápido, bajo recuerdo # # 8 # 64 # 32 #
Equilibrado 16 100 128 128
Alto recuerdo 32 200 256

# Índices de carga útil

Crear [Índices de carga útil](https://qdrant.tech/documentation/concepts/indexing/#payload-index) para campos frecuentemente filtrados:

```csharp
// 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
);
```

**Impacto:** 10-100x filtrado más rápido en grandes colecciones.

# Cuantificación

[Cuantificación](https://qdrant.tech/documentation/guides/quantization/) reduce el uso de memoria:

```csharp
// 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
        }
    }
);
```

**Negociaciones:** 4x menos memoria, ~2% pérdida de memoria, 1.5x búsqueda más rápida.

# Despliegue Docker

```yaml
# 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:
```

## Seguridad

Activar [Autenticación de clave API](https://qdrant.tech/documentation/guides/security/):

```yaml
environment:
  - QDRANT__SERVICE__API_KEY=your-secret-key
```

# Supervisión

## Métricas

Qdrant expone [métricas de prometeo](https://qdrant.tech/documentation/guides/monitoring/) en el `/metrics`:

```bash
curl http://localhost:6333/metrics
```

métricas clave:

- `qdrant_collections_vector_count` - Total de vectores
- `qdrant_rest_responses_duration_seconds` - Latencia de la consulta
- `qdrant_memory_usage_bytes` - Consumo de memoria

## Snapshots

Crear [copias de seguridad](https://qdrant.tech/documentation/concepts/snapshots/):

```bash
# 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 comunes

## 1. Confusión portuaria

- **6333** = API REST
- **6334** = API de gRPC (¡usar esto!)

## 2. Vector Dimension Mismatch

```
Error: expected dim: 384, got 768
```

Su modelo de incrustación y colección deben coincidir con:

- `all-MiniLM-L6-v2`: 384 dimensiones
- `nomic-embed-text`: 768 dimensiones
- OpenAI `text-embedding-3-small`: 1536 dimensiones

## 3. Primera consulta lenta

HNSW carga perezosamente en la memoria. Caliente después de iniciar:

```csharp
await client.SearchAsync("blog_posts", new float[384], limit: 1);
```

## 4. Filtrado de matriz

Uso `Match.Any` para los campos del array:

```csharp
new Match { Any = new RepeatedStrings { Strings = { "AI", "ML" } } }
```

# Recursos

## Documentación oficial de Qdrant

- [Sinopsis](https://qdrant.tech/documentation/overview/) - Comenzando.
- [Conceptos](https://qdrant.tech/documentation/concepts/) - Conceptos básicos
- [Recaudación](https://qdrant.tech/documentation/concepts/collections/) - Creación y gestión de colecciones
- [Puntos](https://qdrant.tech/documentation/concepts/points/) - Trabajar con vectores
- [Buscar](https://qdrant.tech/documentation/concepts/search/) - Operaciones de consulta
- [Filtrado](https://qdrant.tech/documentation/concepts/filtering/) - Condiciones del filtro
- [Indización](https://qdrant.tech/documentation/concepts/indexing/) - HNSW e índices de carga útil
- [Cuantificación](https://qdrant.tech/documentation/guides/quantization/) - Optimización de memoria
- [Seguridad](https://qdrant.tech/documentation/guides/security/) - Autenticación
- [Supervisión](https://qdrant.tech/documentation/guides/monitoring/) - Métrica y telemetría
- [Snapshots](https://qdrant.tech/documentation/concepts/snapshots/) - Copia de seguridad y restaurar

## Bibliotecas de clientes

- [Cliente Qdrant .NET](https://github.com/qdrant/qdrant-dotnet) - Oficial C# SDK
- [Paquete NuGet](https://www.nuget.org/packages/Qdrant.Client) - Última versión

## Artículos relacionados

- [Parte 4: Aplicación de ONNX & Qdrant](/blog/semantic-search-with-onnx-and-qdrant)
- [Parte 5: Búsqueda híbrida y auto-indexación](/blog/rag-hybrid-search-and-indexing)
- [Resumen de la serie RAG](/blog/rag-primer)

## Código fuente

Todo el código disponible en: [github.com/scottgal/mostlylucidweb](https://github.com/scottgal/mostlylucidweb)

- `Mostlylucid.SemanticSearch/Services/QdrantVectorStoreService.cs` - Integración de Qdrant