> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Ricerca

> Panoramica delle funzioni di ricerca di Laravel. Come scegliere tra full-text, vector search, reranking e Laravel Scout in base al caso d'uso.

## Introduzione

Ci sono più modi per aggiungere la ricerca a un'applicazione. Laravel fornisce strumenti integrati che vanno dal match per keyword alla ricerca semantica con AI, senza servizi esterni obbligatori.

```mermaid theme={null}
flowchart TD
    Q["Requisiti di ricerca"]
    Q --> A{"Basta il match keyword?"}
    A -->|Sì| B["Ricerca full-text<br>whereFullText"]
    A -->|No, serve significato| C["Vector search<br>whereVectorSimilarTo"]
    Q --> D{"Serve sync automatica del modello?"}
    D -->|Sì| E["Laravel Scout<br>trait Searchable"]
    Q --> F{"Rerank dei risultati con AI?"}
    F -->|Sì| G["Reranking<br>AI SDK Reranking"]
```

### Confronto

| Funzione               | Servizio esterno                      | Caratteristiche                                        |
| ---------------------- | ------------------------------------- | ------------------------------------------------------ |
| `whereFullText`        | Nessuno                               | Indici full-text integrati di MariaDB/MySQL/PostgreSQL |
| `whereVectorSimilarTo` | Nessuno (PostgreSQL + pgvector)       | Similarità semantica. Richiede AI SDK                  |
| `Reranking`            | Provider AI                           | Riordina qualsiasi set per rilevanza tramite AI        |
| Laravel Scout          | Nessuno (database engine) / opzionale | Sincronizzazione automatica dell'indice                |

***

## Ricerca full-text

Le query `LIKE` non capiscono la lingua. La ricerca full-text usa indici dedicati e tiene conto di parole, forme, punteggio di rilevanza.

MariaDB, MySQL e PostgreSQL la supportano nativamente.

<Warning>
  Supportata su MariaDB, MySQL, PostgreSQL.
</Warning>

### Indici full-text

```php theme={null}
Schema::create('articles', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('body');
    $table->timestamps();

    $table->fullText(['title', 'body']);
});
```

PostgreSQL può indicare la lingua:

```php theme={null}
$table->fullText('body')->language('english');
```

<Info>
  **Nota sulla ricerca full-text in giapponese / italiano non-standard**\
  In MySQL la ricerca full-text non anglofona ha limiti (es. AWS RDS supporta solo N-gram parser). Anche PostgreSQL è limitato per lingue con morfologia complessa. Considera motori dedicati come Meilisearch o Typesense.
</Info>

### Esecuzione

```php theme={null}
$articles = Article::whereFullText('body', 'web developer')->get();
```

Con indice composito:

```php theme={null}
$articles = Article::whereFullText(
    ['title', 'body'], 'web developer'
)->get();
```

<Info>
  MariaDB/MySQL ordinano per rilevanza. In PostgreSQL `whereFullText` filtra soltanto: per l'ordinamento automatico usa il [database engine di Scout](#laravel-scout).
</Info>

Anche `orWhereFullText` per OR. Vedi il [query builder](/it/query-builder).

***

## Ricerca semantica / vettoriale

Il full-text si basa su match di keyword. La vector search usa embedding generati da AI per rappresentare il significato come array numerici e trovare risultati semanticamente vicini.

Esempio: "best wineries in Napa Valley" corrisponde a "Top Vineyards to Visit" pur senza keyword condivise.

<Note>
  Richiede [Laravel AI SDK](/it/ai-sdk). Supporta PostgreSQL (con l'estensione `pgvector`) e MongoDB (con `laravel-mongodb`). [Laravel Cloud](https://laravel.com/cloud) ha `pgvector` preinstallato su tutti i database Postgres.
</Note>

### Generare gli embedding

Con `Stringable::toEmbeddings`:

```php theme={null}
use Illuminate\Support\Str;

$embedding = Str::of('Napa Valley has great wine.')->toEmbeddings();
```

Batch con `Embeddings`:

```php theme={null}
use Laravel\Ai\Embeddings;

$response = Embeddings::for([
    'Napa Valley has great wine.',
    'Laravel is a PHP framework.',
])->generate();

$response->embeddings;
```

Vedi la [documentazione dell'AI SDK](/it/ai-sdk) per configurazione e dimensioni.

### Salvataggio e indicizzazione

Colonna `vector` in migration:

```php theme={null}
Schema::ensureVectorExtensionExists();

Schema::create('documents', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content');
    $table->vector('embedding', dimensions: 1536)->index();
    $table->timestamps();
});
```

Cast in `array`:

```php theme={null}
protected function casts(): array
{
    return [
        'embedding' => 'array',
    ];
}
```

Vedi [Migration](/it/migrations).

### Ricerca per similarità

```php theme={null}
$documents = Document::query()
    ->whereVectorSimilarTo('embedding', $queryEmbedding, minSimilarity: 0.4)
    ->limit(10)
    ->get();
```

Passando una stringa, Laravel calcola l'embedding.

```php theme={null}
$documents = Document::query()
    ->whereVectorSimilarTo('embedding', 'best wineries in Napa Valley')
    ->limit(10)
    ->get();
```

Anche `whereVectorDistanceLessThan`, `selectVectorDistance`, `orderByVectorDistance`.

***

## Reranking

L'AI riordina un set di risultati per rilevanza rispetto alla query. Diversa dalla vector search: non richiede embedding preesistenti e si applica a qualsiasi collezione di testo.

Pattern efficace: **filtra veloce + rerank**.

```php theme={null}
use Laravel\Ai\Reranking;

$response = Reranking::of([
    'Django is a Python web framework.',
    'Laravel is a PHP web application framework.',
    'React is a JavaScript library for building user interfaces.',
])->rerank('PHP frameworks');

$response->first()->document;
```

Le Collection Laravel hanno la macro `rerank`.

```php theme={null}
$articles = Article::all()
    ->rerank('body', 'Laravel tutorials');
```

Vedi la [documentazione dell'AI SDK](/it/ai-sdk).

***

## Laravel Scout

Fin qui abbiamo usato metodi del query builder. [Laravel Scout](/it/scout) è diverso: aggiungi il trait `Searchable` e Scout sincronizza automaticamente gli indici.

### Database engine

Full-text + `LIKE` sul DB esistente. Senza servizi esterni.

```php theme={null}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Attributes\SearchUsingFullText;
use Laravel\Scout\Attributes\SearchUsingPrefix;
use Laravel\Scout\Searchable;

class Article extends Model
{
    use Searchable;

    #[SearchUsingPrefix(['id'])]
    #[SearchUsingFullText(['title', 'body'])]
    public function toSearchableArray(): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'body' => $this->body,
        ];
    }
}
```

| Attributo             | Strategia                                     |
| --------------------- | --------------------------------------------- |
| `SearchUsingFullText` | Full-text (`MATCH...AGAINST` / `to_tsvector`) |
| `SearchUsingPrefix`   | Prefisso (`example%`)                         |
| Nessuno               | Wildcard davanti/dietro (`%example%`)         |

<Warning>
  Serve un [indice full-text](/it/migrations).
</Warning>

```php theme={null}
$articles = Article::search('Laravel')->get();
```

Il database engine di Scout ordina per rilevanza anche in PostgreSQL.

### Motori di terze parti

Scout supporta [Algolia](https://www.algolia.com/), [Meilisearch](https://www.meilisearch.com), [Typesense](https://typesense.org). API unificata: puoi migrare cambiando poco.

<Note>
  Non serve a tutti. I metodi integrati coprono la maggior parte dei casi.
</Note>

Vedi la [guida a Laravel Scout](/it/scout).

***

## Combinazioni

### Full-text + Reranking

Filtra veloce con full-text, poi rerank con AI.

```php theme={null}
$articles = Article::query()
    ->whereFullText('body', $request->input('query'))
    ->limit(50)
    ->get()
    ->rerank('body', $request->input('query'), limit: 10);
```

### Vector + filtri classici

Restringi a un tenant e cerca per similarità.

```php theme={null}
$documents = Document::query()
    ->where('team_id', $user->team_id)
    ->whereVectorSimilarTo('embedding', $request->input('query'))
    ->limit(10)
    ->get();
```

***

## Pagine correlate

<Card title="Laravel Scout" icon="magnifying-glass" href="/it/scout">
  Guida completa alla sincronizzazione automatica degli indici.
</Card>

<Card title="Laravel AI SDK" icon="sparkles" href="/it/ai-sdk">
  Configurazione dell'AI SDK per embedding e reranking.
</Card>

<Card title="Query Builder" icon="database" href="/it/query-builder">
  Dettagli su whereFullText, whereVectorSimilarTo, ecc.
</Card>

<Card title="Migration" icon="table" href="/it/migrations">
  Creazione di indici full-text e colonne vector.
</Card>


## Related topics

- [Basic client - Laravel Bluesky](/it/packages/laravel-bluesky/basic-client.md)
- [Aggiornamenti Laravel di marzo 2026](/it/blog/changelog/202603.md)
- [Riepilogo delle novità di Laravel 13](/it/blog/laravel-13-new-features.md)
- [Laravel e lo sviluppo con AI](/it/ai.md)
- [Laravel AI SDK](/it/ai-sdk.md)
