Query composta — SDK v9
Compound query — SDK v9
import {
getFirestore, collection, query,
where, orderBy, limit, getDocs
} from 'firebase/firestore';
const db = getFirestore();
/**
* Recupera le richieste di un operatore degli ultimi N giorni.
* Questa query richiede un indice composito su:
* [operatorId ASC, tipo ASC, timestamp DESC]
*/
async function getRecentRequests(operatorId, giorni = 90) {
const cutoff = Date.now() - giorni * 24 * 60 * 60 * 1000;
const q = query(
collection(db, 'activityLog'),
where('operatorId', '==', operatorId),
where('tipo', 'in', ['ferie', 'permesso', 'malattia']),
where('timestamp', '>=', cutoff),
orderBy('timestamp', 'desc'),
limit(100)
);
const snap = await getDocs(q);
return snap.docs.map(d => ({ id: d.id, ...d.data() }));
}
Errore tipico in console:
FirebaseError: The query requires an index. You can create it here: https://console.firebase.google.com/...
Il link nell'errore porta direttamente alla creazione dell'indice. Cliccalo e attendi 1-2 minuti.
Typical console error:
FirebaseError: The query requires an index. You can create it here: https://console.firebase.google.com/...
The link in the error goes directly to the index creation page. Click it and wait 1-2 minutes.
Come funziona un indice composito
Firestore crea automaticamente indici su ogni singolo campo. Quando combini più campi in una query — specialmente con orderBy() su un campo diverso da quello filtrato — Firestore non può usare gli indici singoli e ne richiede uno composito che copra tutti i campi coinvolti.
Regole pratiche:
- Uguaglianza semplice
== su un campo → nessun indice composito
- Due o più
where() su campi diversi → indice composito richiesto
where() + orderBy() su campi diversi → indice composito richiesto
in, array-contains-any → richiedono indice se combinati con altri filtri
How a composite index works
Firestore automatically creates indexes for every individual field. When you combine multiple fields in a query — especially using orderBy() on a different field from the one being filtered — Firestore can't use single-field indexes and requires a composite one covering all fields involved.
Practical rules:
- Simple equality
== on one field → no composite index needed
- Two or more
where() on different fields → composite index required
where() + orderBy() on different fields → composite index required
in, array-contains-any → require an index when combined with other filters
Crea l'indice manualmente (senza aspettare l'errore)
Create the index manually (without waiting for the error)
{
"indexes": [
{
"collectionGroup": "activityLog",
"queryScope": "COLLECTION",
"fields": [
{ "fieldPath": "operatorId", "order": "ASCENDING" },
{ "fieldPath": "tipo", "order": "ASCENDING" },
{ "fieldPath": "timestamp", "order": "DESCENDING" }
]
}
],
"fieldOverrides": []
}
Strategia consigliata: sviluppa in locale, lascia che l'errore in console ti fornisca il link la prima volta, clicca per creare l'indice, poi esporta la configurazione con firebase firestore:indexes e committala nel progetto.
Recommended strategy: develop locally, let the console error give you the link the first time, click to create the index, then export the config with firebase firestore:indexes and commit it to your project.
Limiti da tenere a mente
- Firestore supporta al massimo 200 indici compositi per progetto
- Una query con
in su N valori esegue N sotto-query internamente
- Non puoi avere due filtri di disuguaglianza (
>, <) su campi diversi nella stessa query
- L'indice impiega 1-3 minuti per diventare attivo — ricarica la pagina dopo la creazione
Limits to keep in mind
- Firestore supports a maximum of 200 composite indexes per project
- A query with
in on N values runs N sub-queries internally
- You can't have two inequality filters (
>, <) on different fields in the same query
- The index takes 1-3 minutes to become active — reload the page after creation
Articolo correlato
Centro notifiche PWA: sei categorie, due database — Firestore in produzione
Related article
PWA notification centre: six categories, two databases — Firestore in production
→
Articolo correlato
E-commerce custom su Firebase: query Firestore per varianti, ordini atomici e admin panel
Related article
Custom Firebase e-commerce: Firestore queries for variants, atomic orders and admin panel
→