# RAG per implementatori: Ricerca ibrida e Indicizzazione automatica

<datetime class="hidden">2025-11-22T12:00</datetime>

<!-- category -- ASP.NET, Semantic Search, ONNX, Qdrant, Machine Learning, Vector Search, RAG, AI-Article -->
# Introduzione

**Parte della serie RAG:** Questa è la parte 5 - schemi di integrazione della produzione:

- [Parte 1: Origini e fondamenti degli orientamenti](/blog/rag-primer) - Che cosa sono le inserzioni, perché contano
- [Parte 2: Architettura e interni RAG](/blog/rag-architecture) - Chunking, tokenisation, database vettoriali
- [Parte 3: RAG nella pratica](/blog/rag-practical-applications) - Costruire sistemi RAG completi
- [Parte 4a: Implementazione di ONNX & Qdrant](/blog/semantic-search-with-onnx-and-qdrant) - CPU-friendly fondazione di ricerca semantica
- [Parte 4b: Ricerca semantica in azione](/blog/semantic-search-in-action) - Typeahead, ricerca ibrida e componenti UI
- **Parte 5: Ricerca ibrida e integrazione automatica** (questo articolo) - Modelli di integrazione della produzione
- [Parte 6: GraphRAG](/blog/graphrag-knowledge-graphs-for-rag) - Grafici della conoscenza per la comprensione a livello di corpus

Dentro [Parte 4a](/blog/semantic-search-with-onnx-and-qdrant), abbiamo costruito la fondazione: ONNX embeddings e Qdrant storage. In [Parte 4b](/blog/semantic-search-in-action), abbiamo coperto l'interfaccia utente di ricerca e l'implementazione di ricerca ibrida. **indicizzazione automatica** (aggiornamenti contenuti a zero touch) tramite FileSystemWatcher.

[TOC]

# Ricerca ibrida: Il meglio di entrambi i mondi

La ricerca semantica è potente ma la ricerca full-text tradizionale eccelle ancora a frasi esatte e termini tecnici. **La soluzione?** Usa entrambe le cose.

**Perché Hybrid?** I diversi approcci hanno diversi punti di forza:

- **PostgreSQL Full-Text** ([qui coperto](/blog/textsearchingpt1)): Corrispondenze esatte, termini tecnici, operatori booleani
- **Ricerca vettoriale semantica**: Significato, contesto, sinonimi, contenuto concettualmente correlato

## Fusione di Rank reciproco (RRF)

Noi usiamo **Fusione di Rank reciproco** per combinare i risultati di più fonti di ricerca:

```mermaid
flowchart TB
    A[User Query: 'docker containers'] --> B[PostgreSQL Full-Text Search]
    A --> C[Semantic Vector Search]

    B --> D["Results:<br/>1. 'Docker Basics' (rank 1)<br/>2. 'Containerizing Apps' (rank 2)<br/>3. 'Docker Compose' (rank 3)"]
    C --> E["Results:<br/>1. 'Containerizing Apps' (rank 1)<br/>2. 'Kubernetes Guide' (rank 2)<br/>3. 'Docker Basics' (rank 3)"]

    D --> F[RRF Algorithm]
    E --> F

    F --> G["Combined Results:<br/>1. 'Containerizing Apps'<br/>   (1/61 + 1/62 = 0.0328)<br/>2. 'Docker Basics'<br/>   (1/61 + 1/63 = 0.0322)<br/>3. 'Docker Compose'<br/>   (1/63 = 0.0159)"]

    style A stroke:#10b981,stroke-width:2px
    style B stroke:#3b82f6,stroke-width:2px
    style C stroke:#6366f1,stroke-width:2px
    style D stroke:#3b82f6,stroke-width:2px
    style E stroke:#6366f1,stroke-width:2px
    style F stroke:#ec4899,stroke-width:4px
    style G stroke:#8b5cf6,stroke-width:2px
```

**La formula RRF:** `score = Σ(1 / (k + rank))`

- `k` = 60 (costante per evitare la dominazione dei ranghi primitivi)
- `rank` = posizione nei risultati del metodo di ricerca
- Risultati in **entrambi** le fonti ottengono punteggi da ogni sommato

**Perché RRF funziona:**

- **Deduplicazione**: Stesso risultato in entrambe le fonti punteggio più alto
- **Equità**: Nessun metodo di ricerca domina ingiustamente
- **Semplicità**: Non è richiesta alcuna messa a punto complessa

## Attuazione

```csharp
public class HybridSearchService : IHybridSearchService
{
    private readonly ISemanticSearchService _semanticSearchService;
    private const int RrfConstant = 60;

    public async Task<List<SearchResult>> SearchAsync(
        string query,
        string language = "en",
        int limit = 10,
        CancellationToken cancellationToken = default)
    {
        // Execute both searches in parallel
        var semanticResults = await _semanticSearchService.SearchAsync(
            query, limit * 2, cancellationToken);

        // Filter by language and apply RRF
        var filteredResults = semanticResults
            .Where(r => r.Language == language)
            .ToList();

        return ApplyReciprocalRankFusion(filteredResults)
            .Take(limit)
            .ToList();
    }

    private List<SearchResult> ApplyReciprocalRankFusion(List<SearchResult> results)
    {
        var rrfScores = new Dictionary<string, RrfScore>();

        for (int i = 0; i < results.Count; i++)
        {
            var result = results[i];
            var key = $"{result.Slug}_{result.Language}";

            if (!rrfScores.ContainsKey(key))
                rrfScores[key] = new RrfScore { Result = result };

            // RRF formula: 1 / (k + rank)
            rrfScores[key].Score += 1.0 / (RrfConstant + i + 1);
        }

        return rrfScores.Values
            .OrderByDescending(x => x.Score)
            .Select(x => x.Result)
            .ToList();
    }
}
```

> **Nota:** Questo mostra solo la ricerca semantica. In produzione, eseguire la ricerca postgreSQL full-text in parallelo e includere i risultati nel calcolo RRF.

## Integrazione

Se hai già implementato PostgreSQL ricerca full-text ([come qui coperto](/blog/textsearchingpt1)), l'aggiunta di ricerca semantica è semplice:

```csharp
// Program.cs
services.AddSemanticSearch(configuration);
services.AddSingleton<IHybridSearchService, HybridSearchService>();
```

```csharp
[HttpGet("search/hybrid")]
public async Task<IActionResult> HybridSearch(string query, string language = "en")
{
    var results = await _hybridSearchService.SearchAsync(query, language);
    return PartialView("_SearchResults", results);
}
```

# Indicizzazione automatica con l'Osservatore di File System

La caratteristica più potente: **indicizzazione automatica**. Salvare un post sul blog, è immediatamente ricercabile - nessun intervento manuale.

## Come funziona

```mermaid
flowchart TB
    A[Save Markdown File] --> B[FileSystemWatcher Detects Change]
    B --> C{File in Main Directory?}
    C -->|Yes| D[Save to Database]
    C -->|No| E[Save to Database Only]
    D --> F[Create BlogPostDocument]
    F --> G[Generate Embedding via ONNX]
    G --> H[Store in Qdrant]
    H --> I[Post Searchable Immediately]

    style A stroke:#10b981,stroke-width:2px
    style B stroke:#f59e0b,stroke-width:2px
    style C stroke:#ec4899,stroke-width:3px
    style D stroke:#3b82f6,stroke-width:2px
    style E stroke:#6b7280,stroke-width:2px
    style F stroke:#8b5cf6,stroke-width:2px
    style G stroke:#6366f1,stroke-width:3px
    style H stroke:#ef4444,stroke-width:2px
    style I stroke:#10b981,stroke-width:2px
```

**Decisione chiave in materia di progettazione:** Solo i file indice nel **directory Markdown principale**, non sottodirectory (`translated/`, `drafts/`, `comments/`). Questo mantiene pulito l'indice di ricerca.

## Integrazione con l'Osservatore di file

Il blog ha già un `MarkdownDirectoryWatcherService`Lo estendiamo per innescare l'indicizzazione semantica:

```csharp
// In MarkdownDirectoryWatcherService.cs
private async Task OnChangedAsync(WaitForChangedResult e)
{
    if (e.Name == null) return;

    await retryPolicy.ExecuteAsync(async () =>
    {
        var savedModel = await blogService.SavePost(slug, language, markdown);

        // Index ONLY if file is in main directory (no path separators in name)
        if (!e.Name.Contains(Path.DirectorySeparatorChar) &&
            !e.Name.Contains(Path.AltDirectorySeparatorChar))
        {
            await IndexPostForSemanticSearchAsync(scope, savedModel, language);
        }
    });
}

private async Task IndexPostForSemanticSearchAsync(
    IServiceScope scope,
    BlogPostDto post,
    string language)
{
    var semanticSearchService = scope.ServiceProvider.GetService<ISemanticSearchService>();
    if (semanticSearchService == null) return; // Not configured

    var document = new BlogPostDocument
    {
        Id = $"{post.Slug}_{language}",
        Slug = post.Slug,
        Title = post.Title,
        Content = post.PlainTextContent,
        Language = language,
        Categories = post.Categories?.ToList() ?? new List<string>(),
        PublishedDate = post.PublishedDate
    };

    await semanticSearchService.IndexPostAsync(document);
    _logger.LogInformation("Indexed {Slug} ({Language}) in semantic search", post.Slug, language);
}
```

## Cancellazioni di manipolazione

Quando un post viene eliminato, rimuoverlo dall'indice semantico:

```csharp
private async Task OnDeletedAsync(WaitForChangedResult e)
{
    await blogService.Delete(slug, language);

    // Delete from semantic search ONLY if file was in main directory
    if (!e.Name.Contains(Path.DirectorySeparatorChar) &&
        !e.Name.Contains(Path.AltDirectorySeparatorChar))
    {
        var semanticSearchService = scope.ServiceProvider.GetService<ISemanticSearchService>();
        await semanticSearchService?.DeletePostAsync(slug, language);
    }
}
```

# Servizio di sfondo per l'indicizzazione iniziale

All'avvio, un servizio di background indici i post esistenti non ancora in Qdrant:

```mermaid
flowchart TB
    A[Application Starts] --> B[Wait 10 seconds]
    B --> C[Initialize Semantic Search]
    C --> D{Model Exists?}
    D -->|No| E[Download from Hugging Face]
    D -->|Yes| F[Load ONNX Model]
    E --> F
    F --> G[Scan Main Markdown Directory]
    G --> H{For Each .md File}
    H --> I[Compute Content Hash]
    I --> J{Hash Changed?}
    J -->|Yes| K[Generate Embedding]
    J -->|No| L[Skip - Already Indexed]
    K --> M[Store in Qdrant]
    M --> H
    L --> H
    H -->|Done| N[Indexing Complete]

    style A stroke:#10b981,stroke-width:2px
    style C stroke:#6366f1,stroke-width:2px
    style E stroke:#f59e0b,stroke-width:2px
    style F stroke:#6366f1,stroke-width:3px
    style G stroke:#8b5cf6,stroke-width:2px
    style J stroke:#ec4899,stroke-width:3px
    style K stroke:#6366f1,stroke-width:2px
    style M stroke:#ef4444,stroke-width:2px
    style N stroke:#10b981,stroke-width:2px
```

```csharp
public class SemanticIndexingBackgroundService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        // Wait for app to be ready
        await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);

        // Initialize (downloads model if needed)
        await _semanticSearchService.InitializeAsync(stoppingToken);

        // Get all posts from main directory only
        var markdownFiles = Directory.GetFiles(
            _markdownConfig.MarkdownPath,
            "*.md",
            SearchOption.TopDirectoryOnly);  // NOT subdirectories

        foreach (var file in markdownFiles)
        {
            var needsIndexing = await _semanticSearchService.NeedsReindexingAsync(
                slug, language, contentHash, stoppingToken);

            if (needsIndexing)
                await _semanticSearchService.IndexPostAsync(document, stoppingToken);
        }
    }
}
```

**Ciò garantisce:**

1. **Caricamento del modello pigro** - Download al primo utilizzo, non blocca l'avvio
2. **Indicizzazione incrementale** - Solo i nuovi posti/cambiati ri-indexed (tramite hash contenuto)
3. **Solo directory principale** - Bozze e file tradotti non inquinano l'indice

# Quello che abbiamo costruito

Attraverso le parti 4a, 4b e 5, ora abbiamo:

- ✅ **CPU-friendly ricerca semantica** - Nessuna GPU richiesta
- ✅ **Related posts discovery** - Contenuto semanticamente simile
- ✅ **Ricerca linguistica naturale** - Trovare per significato, non solo parole chiave
- ✅ **Ricerca ibrida** - Best of semantic + full-text
- ✅ **Indexing automatico** - Aggiornamenti contenuti Zero-Touch
- ✅ **Auto-ospitalità** - I tuoi dati rimangono sul tuo server

**Miglioramenti futuri:**

- **Ricerca di categoria-consapevole** - Aumentare i risultati di categorie specifiche
- **Abbinamenti multilingue** - Modelli specifici per l'integrazione delle lingue
- **Integrazione OpenSearch** - Aggiungi OpenSearch al mix ibrido ([vedi il mio articolo OpenSearch](/blog/textsearchingpt3))

# Conclusione

Ciò completa l'attuazione pratica della ricerca semantica in stile RAG. [Parte 4a](/blog/semantic-search-with-onnx-and-qdrant) (fondazione) e [Parte 4b](/blog/semantic-search-in-action) (search UI), hai tutto il necessario per aggiungere la ricerca intelligente alla tua applicazione .NET - in esecuzione interamente su CPU, a zero costi aggiuntivi.

## Continua ad imparare

- **[RAG Parte 1: Origini e Fondamenti](/blog/rag-primer)** - La teoria dietro l'imbottitura
- **[RAG Parte 2: Architettura e Interni](/blog/rag-architecture)** - Immersione profonda nei sistemi RAG
- **[RAG Parte 3: Applicazioni pratiche](/blog/rag-practical-applications)** - RAG completi con integrazione LLM
- **[Parte 4a: Implementazione di ONNX & Qdrant](/blog/semantic-search-with-onnx-and-qdrant)** - Fondazione: inglobamenti e stoccaggio vettoriale
- **[Parte 4b: Ricerca semantica in azione](/blog/semantic-search-in-action)** - Typeae, ricerca ibrida e UI
- **[Ricerca full-text con PostgreSQL](/blog/textsearchingpt1)** - Il lato full-text della ricerca ibrida

## Risorse

### Banca dati Qdrant e vettori

- [Database vettoriali self-hosted con Qdrant](/blog/self-hosted-vector-databases-qdrant) - Immersione profonda in concetti Qdrant, indicizzazione HNSW, filtraggio e client C#
- [Ricerca ibrida Qdrant](https://qdrant.tech/documentation/concepts/hybrid-queries/) - Supporto ibrido nativo di Qdrant

### Ricerca ibrida

- [Carta per fusione a rango reciproco](https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf) - L'algoritmo RRF

### Controllo file system

- [Classe FileSystemWatcher](https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher) - Documentazione .NET
- [Classe BackgroundService](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.backgroundservice) - Servizi ospitati in ASP.NET Core

### Codice completo

Tutti i codici sono disponibili al seguente indirizzo: [github.com/scottgal/mostlylucidweb](https://github.com/scottgal/mostlylucidweb)

- `Mostlylucid.SemanticSearch/` - Core libreria di ricerca semantica
- `Mostlylucid/Blog/WatcherService/` - Osservatore di file con indicizzazione semantica