# Omatoimiset Vektori-tietokannat Qdrantilla: Deep Dive

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

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

**RAG-sarjaan liittyvät tiedot:** Tässä artikkelissa sukeltaa syvälle Qdrantiin, vektoritietokantaan, jota käytetään:

- [Osa 4: ONNX- ja Qdrant-toteutus](/blog/semantic-search-with-onnx-and-qdrant) - Rakentaa semanttista etsintää
- [Osa 5: Hybridihaku ja autoindeksointi](/blog/rag-hybrid-search-and-indexing) - Tuotantointegraatio

[Qdrant](https://qdrant.tech/) (julkaistu "quadrant") on avoimen lähdekoodin vektoritietokanta, joka on rakennettu Rustiin. Artikkelissa käsitellään ydinkonsepteja, C#-asiakasta, suoritusten viritystä ja tuotantomalleja.

[TOC]

# Mikä Qdrant on?

A [vektoritietokanta](https://qdrant.tech/documentation/overview/) tallentaa suuriulotteisia vektoreita (embedings) ja mahdollistaa nopean samankaltaisuushaun. Toisin kuin perinteiset tietokannat, jotka löytävät täsmällisiä osuuksia, Qdrant löytää *Semanttisesti samanlainen* kohteita.

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

**Tärkeimmät Qdrantin ominaisuudet:**

- [HNSW-indeksointi](https://qdrant.tech/documentation/concepts/indexing/) - Sublineaariset hakuajat
- [Suodatus](https://qdrant.tech/documentation/concepts/filtering/) - Yhdistä samankaltaisuushaku metatietosuodattimiin
- [gRPC- ja REST-rajapinnat](https://qdrant.tech/documentation/interfaces/) - Korkean suorituskyvyn saavutettavuus
- [Hajautettu käyttöönotto](https://qdrant.tech/documentation/guides/distributed_deployment/) - Skaalaa vaakatasossa
- [Snapshootit](https://qdrant.tech/documentation/concepts/snapshots/) - Varmuuskopiointi ja restaurointi

# Keskeisiä käsitteitä

## Kokoelmat

A [kokoelma](https://qdrant.tech/documentation/concepts/collections/) on kuin pöytä - siinä on vektoreita, joilla on kiinteä ulottuvuus ja etäisyys metrillä.

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

**Etäisyysmittarit** ([docs](https://qdrant.tech/documentation/concepts/collections/#distance-metrics)):

- **Cosine** - Mittauskulma vektorien välillä (paras tekstiksi)
- **Piste** - Raaka sisäinen tuote (esinormalisoituja vektoreita varten)
- **Eukleides** - Geometrinen etäisyys (paikkatietojen osalta)

## Pisteet

A [piste](https://qdrant.tech/documentation/concepts/points/) on yksi levy, joka sisältää:

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

## Suodatus

[Suodatus](https://qdrant.tech/documentation/concepts/filtering/) juoksee *ennen* samankaltaisuushaku - erittäin tehokas.

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

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

- `Match.Keyword` - Tarkka merkkijono täsmää
- `Match.Text` - Täystekstiotos
- `Match.Any` - Sopivat yhteen kaikkien kanssa
- `Range` - Numeeriset vaihteluvälit (Gte, Lte, Gt, Lt)
- `GeoBoundingBox` / `GeoRadius` - Geosuodatus

# C#-asiakas

Asenna virkamies [Qdrant.Client](https://www.nuget.org/packages/Qdrant.Client) paketti ([GitHub](https://github.com/qdrant/qdrant-dotnet)):

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

## Liitännäisasetukset

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

> **Käytä aina gRPC:tä** (portti 6334) tuotantoon - 3-5x RESTiä nopeammin.

## Windows HTTP/2 Korjataan

Ota Windowsissa käyttöön salaamaton HTTP/2 **ennen** asiakkaan luominen:

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

## Avaintoiminnot

### Etsi

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

### Erän 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
);
```

### Poista

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

# HNSW-indeksin viritys

[HNSW](https://qdrant.tech/documentation/concepts/indexing/#vector-index) (Hierarkical Navigable Small World) on Qdrantin indeksialgoritmi.

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

## Indeksimuuttujat

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

**Hakuajan tarkkuus:**

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

**Suuntaviivojen virittäminen:**
HnswEf, HnswEf, EfConstruct
|----------|---|-------------|--------|
Nopeaa, matalaa muistia 8 64 32
Tasapainoinen 16 1 2 2 2 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
"High recall 32 200 256"

# Hyödyllisyysindeksit

Luo [hyötykuormaindeksit](https://qdrant.tech/documentation/concepts/indexing/#payload-index) usein suodatetut kentät:

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

**Vaikutus:** 10-100x nopeampaa suodatusta suuriin kokoelmiin.

# Kvantifiointi

[Kvantifiointi](https://qdrant.tech/documentation/guides/quantization/) vähentää muistin käyttöä:

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

**Kaupankäynti:** 4x vähemmän muistia, ~2% muistinmenetystä, 1,5x nopeampi haku.

# Dockerin käyttöönotto

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

## Turvallisuus

Käytä [API-avaimen tunnistaminen](https://qdrant.tech/documentation/guides/security/):

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

# Seuranta

## Metriikka

Qdrant paljastaa [Prometheusmittarit](https://qdrant.tech/documentation/guides/monitoring/) @ info: whatsthis `/metrics`:

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

Avainmittarit:

- `qdrant_collections_vector_count` - Kokonaisvektorit
- `qdrant_rest_responses_duration_seconds` Query latenssi
- `qdrant_memory_usage_bytes` - Muistinkulutus

## Snapshootit

Luo [varmuuskopiot](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/)
```

# Common Gotchas

## 1. Portin sekavuus

- **6333** = REST API
- **6334** = gRPC API (käytä tätä!)

## 2. Vektoriulottuvuus Mismatch

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

Upotettavan mallisi ja kokoelmasi on vastattava:

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

## 3. Hidas ensimmäinen kysely

HNSW laiskottelee muistiin. Lämpenee käynnistyksen jälkeen:

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

## 4. Array-suodatus

Käyttö `Match.Any` sarjoittaiskentät:

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

# Resurssit

## Virallinen Qdrant-dokumentaatio

- [Yleiskatsaus](https://qdrant.tech/documentation/overview/) - Aloitan.
- [Käsitteet](https://qdrant.tech/documentation/concepts/) - Keskeisiä käsitteitä
- [Kokoelmat](https://qdrant.tech/documentation/concepts/collections/) - Kokoelmien luominen ja johtaminen
- [Pisteet](https://qdrant.tech/documentation/concepts/points/) - Työskentely vektorien kanssa
- [Etsi](https://qdrant.tech/documentation/concepts/search/) - Kyselyt
- [Suodatus](https://qdrant.tech/documentation/concepts/filtering/) - Suodatusolosuhteet
- [Hakemisto](https://qdrant.tech/documentation/concepts/indexing/) - HNSW- ja hyötykuormaindeksit
- [Kvantifiointi](https://qdrant.tech/documentation/guides/quantization/) - Muistin optimointi
- [Turvallisuus](https://qdrant.tech/documentation/guides/security/) - Tunnistus
- [Seuranta](https://qdrant.tech/documentation/guides/monitoring/) - Metriikka ja telemetria
- [Snapshootit](https://qdrant.tech/documentation/concepts/snapshots/) - Varmuuskopiointi ja restaurointi

## Asiakaskirjastot

- [Qdrant .NET-asiakas](https://github.com/qdrant/qdrant-dotnet) - Virallinen C# SDK
- [NuGet-paketti](https://www.nuget.org/packages/Qdrant.Client) - Uusin julkistus

## Aiheeseen liittyvät artikkelit

- [Osa 4: ONNX- ja Qdrant-toteutus](/blog/semantic-search-with-onnx-and-qdrant)
- [Osa 5: Hybridihaku ja autoindeksointi](/blog/rag-hybrid-search-and-indexing)
- [RAG-sarjan yleiskatsaus](/blog/rag-primer)

## Lähdekoodi

Kaikki koodit saatavilla osoitteessa: [github.com/scottgal/mostlylucidweb](https://github.com/scottgal/mostlylucidweb)

- `Mostlylucid.SemanticSearch/Services/QdrantVectorStoreService.cs` - Qdrant-integraatio