# Самої-Схований векторні бази з Qdrant: Глибокий дайвинг

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

<!-- category -- ASP.NET, Semantic Search, Vector Databases, Qdrant, RAG, AI-Article -->
# Введение

**📖 Подібні до серії RAG** Ця стаття дає глибокий подив на Qdrant, векторну базу даних, використану вM SK1

- [Частина 4: ONNX & Введення гарантійного](/blog/semantic-search-with-onnx-and-qdrant) - Збудування семантичного пошуку
- [Частина 5: Гібридне пошук МSK1 АвтоM SK2 Індексування](/blog/rag-hybrid-search-and-indexing) - Інтеграція виробництва

[Кдрант](https://qdrant.tech/) (промовлено "квадрант МSK2 - це відкритий МSK3 базу даних векторів вихідних даних, збудований в Рості СМСК4 Цей artykuł охоплює основні концепції МСК5 C СМСК6 клієнта МСК7 досконалення продуктивності ВМСК8 і моделі виробництва УМСК9

[TOC]

# Що таке Qdrant?

А [векторна база даних](https://qdrant.tech/documentation/overview/) зберігає високовимірні вектори (вбудованіVSK2 і дає можливість швидкого пошуку подібностіM SK3 Всупереч традиційним базам даних, які знаходять точні співпадіння *семантично схожі* توکي.

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

**Ключові характеристики Qdrant:**

- [Індексування HNSW](https://qdrant.tech/documentation/concepts/indexing/) - СубM SK1лінійні часи пошуку
- [Фильтрування](https://qdrant.tech/documentation/concepts/filtering/) - Об 'єднати пошук схожості з метаданними
- [gRPC & РEST APIs](https://qdrant.tech/documentation/interfaces/) - високий МSK1видатний доступ
- [Розповсюджене використання](https://qdrant.tech/documentation/guides/distributed_deployment/) - Зрівнювати горизонтально
- [Снапшоти](https://qdrant.tech/documentation/concepts/snapshots/) - Бакунок і відновлення

# Корінні концепції

## Коллекції

А [збирання](https://qdrant.tech/documentation/concepts/collections/) як таблиця - вона містить вектори з фіксованим вимірюваністю та відстаніметричними

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

**Відстані вимірювання** ([Документи](https://qdrant.tech/documentation/concepts/collections/#distance-metrics)):

- **Козин** - виміряє кут між векторами  найкращий для тексту МSK2
- **Точка** - Хворий внутрішній продукт  для передшнього МSK2нормалізовані векториМSK3
- **Евклид** - Геометрична відстань МSK1 для просторових данихM SK2

## Помітки

А [точка](https://qdrant.tech/documentation/concepts/points/) є одним записом, що містить:

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

## Фильтрування

[Фильтрування](https://qdrant.tech/documentation/concepts/filtering/) бігає *до цього* пошук подібності - надзвичайно ефективний

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

**Типи фільтрів** ([Документи](https://qdrant.tech/documentation/concepts/filtering/#match)):

- `Match.Keyword` - Точне співпадіння струн
- `Match.Text` - ПолнеM SK1 співпадіння тексту
- `Match.Any` - Match any in array
- `Range` - числові діапазони Gte, LteМSK3 GtM SK4 Lt МSK5
- `GeoBoundingBox` / `GeoRadius` - Геофільтрування

# Клиент C#

Установити офіційну [Qdrant.Client](https://www.nuget.org/packages/Qdrant.Client) пакет ([GitHub](https://github.com/qdrant/qdrant-dotnet)):

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

## Налагодження зв 'язку

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

> **Повсякчас використовувати gRPC** МSK0 порт 6334) для виробництва

## У Windows HTTP/2 виправлення

На Windows, ввімкнути нешифровану HTTP/2 **до цього** створення клієнта:

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

## Ключові операції

### Поиск

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

### Помістити набір

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

### Позбутись

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

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

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

## Параметри індексу

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

**Поиск-точність часуM SK1**

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

**Руководство щодо підготування:**
| Застосунок МSK1 М МSK2 EfConstruct СМСК3 HnswEf СМСК4
|----------|---|-------------|--------|
| Швидкий МSK1 низький зворотній зв 'язок
МSK0 Сбалансований | МSK2 |
| високий ріст повторюваності

# Індекси навантаження

Створити [індекси навантаження](https://qdrant.tech/documentation/concepts/indexing/#payload-index) для часто відфільтрованих pól:

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

**Враження:** 10-100x швидше фільтрування на великих колекціяхM SK1

# Кванталізація

[Кванталізація](https://qdrant.tech/documentation/guides/quantization/) зменшує використання пам 'яті:

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

**Торгівля** 4x менше пам 'ятіM SK1 ~2% втрата пам' ятіМSK3 \1.5x швидший пошук.

# Розгортання Докера

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

## Безпека

Створити [Атентифікація ключів API](https://qdrant.tech/documentation/guides/security/):

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

# Мониторинг

## Метріка

Qdrant розкриває [Метрії Прометеуса](https://qdrant.tech/documentation/guides/monitoring/) на `/metrics`:

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

Ключові метрики:

- `qdrant_collections_vector_count` - Вektorи в цілому
- `qdrant_rest_responses_duration_seconds` - Затримка запити
- `qdrant_memory_usage_bytes` - Споживання пам 'яті

## Снапшоти

Створити [резервні копії](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/)
```

# Повсякденні готча

## 1. Заплутаність порта

- **6333** = РEST API
- **6334** = gRPC API

## 2. Незбіг вимірів вектора

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

Ваші вбудовані моделі та колекції повинні підходити:

- `all-MiniLM-L6-v2`МSK0 384 виміри
- `nomic-embed-text`МSK0 768 виміри
- OpenAI `text-embedding-3-small`МSK0 1536 виміри

## 3. Повільний перший пошук

HNSW занепокоєний-завантаження в пам 'ятьM SK1 Вигрівається після запуску:

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

## 4. ФильтраціяArray

Використовувати `Match.Any` для поля массива:

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

# Ресурс

## офіційна документація про гарантію

- [Перегляньмо](https://qdrant.tech/documentation/overview/) - На початку
- [Концепції](https://qdrant.tech/documentation/concepts/) - Коренные концепції
- [Коллекції](https://qdrant.tech/documentation/concepts/collections/) - Формування та управління колекціями
- [Помітки](https://qdrant.tech/documentation/concepts/points/) - Работа з векторами
- [Поиск](https://qdrant.tech/documentation/concepts/search/) - Операції тесту
- [Фильтрування](https://qdrant.tech/documentation/concepts/filtering/) - умови відфільтрування
- [Індексування](https://qdrant.tech/documentation/concepts/indexing/) - HNSW та індекси навантаження
- [Кванталізація](https://qdrant.tech/documentation/guides/quantization/) - Оптимізація пам 'яті
- [Безпека](https://qdrant.tech/documentation/guides/security/) - Аuthentication
- [Мониторинг](https://qdrant.tech/documentation/guides/monitoring/) - Метріка та телеметрія
- [Снапшоти](https://qdrant.tech/documentation/concepts/snapshots/) - Бакунок і відновлення

## Бібліотеки клієнта

- [Клієнт Qdrant .NET](https://github.com/qdrant/qdrant-dotnet) - Офіціальний CM SK1 SDK
- [Пакет NuGet](https://www.nuget.org/packages/Qdrant.Client) - Останній випуск

## Подібні статті

- [Частина 4: ONNX & Введення гарантійного](/blog/semantic-search-with-onnx-and-qdrant)
- [Частина 5: Гібридне пошук МSK1 АвтоM SK2 Індексування](/blog/rag-hybrid-search-and-indexing)
- [Обзор серії RAG](/blog/rag-primer)

## Источник

Все коди доступні на: [github.comM SK1scottgal/mostlylucidweb](https://github.com/scottgal/mostlylucidweb)

- `Mostlylucid.SemanticSearch/Services/QdrantVectorStoreService.cs` - інтеграція Qdrant