Panoramica delle query con filtri di intervallo e disuguaglianza su più proprietà
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Firestore in modalità Datastore supporta l'utilizzo di filtri di intervallo e di disuguaglianza su più proprietà in una singola query. Questa funzionalità ti offre condizioni di intervallo e disuguaglianza su più proprietà e semplifica lo sviluppo delle applicazioni delegando l'implementazione della logica di post-filtro a Firestore in modalità Datastore.
Filtri di intervallo e disuguaglianza su più proprietà
La seguente query utilizza i filtri di intervallo per priorità e giorni per restituire tutte le attività con priorità superiore a quattro e con meno di tre giorni per il completamento.
Prima di iniziare a eseguire query, assicurati di aver letto
informazioni sulle query.
Se non viene specificata una clausola ORDER BY, Firestore in modalità Datastore utilizza qualsiasi indice che possa soddisfare la condizione di filtro della query per eseguirla. Questo approccio produce un insieme di risultati ordinato in base alla definizione dell'indice.
Per ottimizzare le prestazioni e i costi delle query di Firestore in modalità Datastore,
ottimizza l'ordine delle proprietà nell'indice. A questo scopo, assicurati che l'indice sia ordinato da sinistra a destra in modo che la query si concentri su un set di dati che impedisca la scansione di voci di indice estranee.
Ad esempio, supponiamo che tu voglia cercare in una raccolta di dipendenti per trovare quelli degli Stati Uniti il cui stipendio è superiore a 100.000 $e il cui numero di anni di esperienza è maggiore di 0. In base alla tua conoscenza del
set di dati, sai che il vincolo di stipendio è più selettivo del
vincolo di esperienza. Un indice che riduce il numero di scansioni dell'indice è l'(salary [...], experience [...]). Di conseguenza, una query rapida ed economica ordina salary prima di experience, come mostrato nell'esempio seguente:
Quando ottimizzi gli indici, tieni presente le seguenti best practice.
Ordina le query per uguaglianza seguite dall'intervallo più selettivo o dal campo di disuguaglianza
Firestore in modalità Datastore utilizza le proprietà più a sinistra di un indice composto per soddisfare i vincoli di uguaglianza e, se presenti, i vincoli di intervallo e di disuguaglianza nel primo campo della query orderBy(). Questi vincoli possono ridurre il numero di voci dell'indice analizzate da Firestore in modalità Datastore. Firestore in modalità Datastore utilizza le proprietà rimanenti dell'indice per soddisfare altri vincoli di intervallo e disuguaglianza della query. Questi vincoli non riducono il numero di voci dell'indice che viene esaminato da Firestore in modalità Datastore, ma filtrano le entità non corrispondenti in modo da ridurre il numero di entità restituite ai client.
Ordina le proprietà in ordine decrescente di selettivotà del vincolo di query
Per assicurarti che Firestore in modalità Datastore selezioni l'indice ottimale per la query,
specifica una clausola orderBy() che ordini le proprietà di intervallo e disuguaglianza in base
al grado di selettivo dei relativi vincoli nella query, iniziando da quello più
selettivo. Una maggiore selettività corrisponde a un numero inferiore di entità, mentre una minore selettività corrisponde a un numero maggiore di entità. Nell'ordinamento dell'indice, inserisci le proprietà di intervallo e disuguaglianza con una maggiore selettività prima di quelle con una selettività inferiore.
Per ridurre al minimo il numero di entità che Firestore in modalità Datastore esegue la scansione e restituisce sulla rete, devi sempre ordinare le proprietà in ordine decrescente di selettivorietà dei vincoli di query. Se il set di risultati non è nell'ordine richiesto e si prevede che sia di piccole dimensioni, puoi implementare la logica lato client per riordinarlo in base alle tue aspettative.
Ad esempio, se vuoi cercare in una raccolta di dipendenti per trovare quelli degli Stati Uniti il cui stipendio è superiore a 100.000 $e ordinarli in base all'anno di esperienza del dipendente. Se prevedi che solo un numero ridotto di dipendenti avrà uno stipendio superiore a 100.000 $, un modo efficiente per scrivere la query è il seguente:
Java
Query<Entity>query=Query.newEntityQueryBuilder().setKind("employees").setFilter(PropertyFilter.gt("salary",100000)).setOrderBy(OrderBy("salary")).build();QueryResults<Entity>results=datastore.run(query);// Order results by `experience`
Node.js
constquery=datastore.createQuery("employees").filter(newPropertyFilter("salary",">",100000)).order("salary");const[entities]=awaitdatastore.runQuery(query);// Order results by `experience`
Sebbene l'aggiunta di un ordinamento su experience alla query generi lo stesso insieme di entità ed eviti di riordinare i risultati sui client, la query potrebbe leggere molte più voci di indice estranee rispetto alla query precedente. Questo accade perché
Firestore in modalità Datastore preferisce sempre un indice il cui prefisso delle proprietà dell'indice corrisponde alla
clausola order by della query. Se experience è stato aggiunto alla clausola ORDER BY,
Firestore in modalità Datastore selezionerà l'indice (experience [...], salary [...]) per calcolare i risultati della query. Poiché non ci sono altri vincoli su
experience, Firestore in modalità Datastore leggerà tutte le voci dell'indice della raccolta
employees prima di applicare il filtro salary per trovare il set di risultati finale. Ciò significa che le voci dell'indice che non soddisfano il filtro salary
vengono comunque lette, aumentando così la latenza e il costo della query.
Prezzi
Le query con filtri di intervallo e di disuguaglianza su più proprietà vengono fatturate in base alle entità lette e alle voci dell'indice lette.
Per informazioni dettagliate, consulta la pagina Prezzi.
Limitazioni
Oltre alle limitazioni delle query, tieni presente le seguenti limitazioni prima di
utilizzare query con filtri di intervallo e disuguaglianza su più proprietà:
Per evitare che l'esecuzione delle query diventi troppo costosa, Firestore in modalità Datastore limita il numero di operatori di intervallo o di disuguaglianza a 10.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-05 UTC."],[[["\u003cp\u003eFirestore in Datastore mode allows for range and inequality filters on multiple properties within a single query, simplifying application development.\u003c/p\u003e\n"],["\u003cp\u003eQueries with multiple range and inequality filters can be optimized by ordering properties in the index from most to least selective, to minimize index scans.\u003c/p\u003e\n"],["\u003cp\u003eWhen using the \u003ccode\u003eorderBy()\u003c/code\u003e clause, ensure that it prioritizes equality constraints and the most selective range or inequality fields, followed by other constraints.\u003c/p\u003e\n"],["\u003cp\u003eQueries are billed based on the number of entities and index entries read, and there is a limitation of up to 10 range or inequality operators per query.\u003c/p\u003e\n"],["\u003cp\u003eIt's recommended to read about query optimization, index usage, and performing simple and compound queries for a deeper understanding.\u003c/p\u003e\n"]]],[],null,["# Query with range and inequality filters on multiple properties overview\n\nFirestore in Datastore mode supports using range and inequality filters on multiple properties in a single query. This feature gives you range and inequality conditions on multiple properties and simplifies\nyour application development by delegating implementation of post-filtering\nlogic to Firestore in Datastore mode.\n\nRange and inequality filters on multiple properties\n---------------------------------------------------\n\nThe following query uses range filters on priority and days to return all tasks\nwith priority greater than four and with less than three days to complete. \n\n### Go\n\n query := datastore.NewQuery(\"Task\").\n FilterField(\"priority\", \"\u003e\", 4).\n FilterField(\"days\", \"\u003c\", 3).\n\n### GQL\n\n SELECT * FROM /tasks WHERE priority \u003e 4 AND days \u003c 3;\n\n### Java\n\n Query\u003cEntity\u003e query =\n Query.newEntityQueryBuilder()\n .setKind(\"Task\")\n .setFilter(\n CompositeFilter.and(\n PropertyFilter.gt(\"priority\", 4), PropertyFilter.lt(\"days\", 3)))\n .build();\n\n### Node.js\n\n const query = datastore\n .createQuery('Task')\n .filter(\n and([\n new PropertyFilter('priority', '\u003e', 4),\n new PropertyFilter('days', '\u003c', 3),\n ])\n );\n\n### Python\n\n from google.cloud import https://cloud.google.com/python/docs/reference/datastore/latest/\n client = https://cloud.google.com/python/docs/reference/datastore/latest/.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html()\n query = client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_query(kind=\"Task\")\n query.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.query.Query.html#google_cloud_datastore_query_Query_add_filter(filter=PropertyFilter(\"priority\", \"\u003e\", 4))\n query.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.query.Query.html#google_cloud_datastore_query_Query_add_filter(filter=PropertyFilter(\"days\", \"\u003c\", 3))\n\n### PHP\n\n $query = $datastore-\u003equery()\n -\u003ekind('Task')\n -\u003efilter('priority', '\u003e', 4)\n -\u003efilter('days', '\u003c', 3)\n\n### C#\n\n Query query = new Query(\"Task\")\n {\n Filter = Filter.And(Filter.GreaterThan(\"priority\", 4),\n Filter.LessThan(\"days\", 3))\n };\n\n### Ruby\n\n query = datastore.query(\"Task\")\n .where(\"priority\", \"\u003e\", 4)\n .where(\"days\", \"\u003c\", 3)\n\nIndexing considerations\n-----------------------\n\nBefore you start running queries, make sure you have read\nabout [queries](/datastore/docs/concepts/queries).\n\nIf an `ORDER BY` clause isn't specified, Firestore in Datastore mode uses any index that\ncan satisfy the query's filter condition to serve the query. This approach produces a result\nset that is ordered according to the index definition.\n\nTo optimize the performance and cost of Firestore in Datastore mode queries,\noptimize the order of properties in the index. To do this, ensure that your\nindex is ordered from left to right so that the query distills to a\ndataset that prevents scanning of extraneous index entries.\n\nFor example, suppose you want to search through a collection of employees to\nfind United States employees whose salary is more than $100,000 and whose number\nof years of experience is greater than 0. Based on your understanding of the\ndataset, you know that the salary constraint is more selective than the\nexperience constraint. An index that reduces the number of index scans is the\n`(salary [...], experience [...])` index. As a result, a fast and cost-efficient\nquery orders `salary` before `experience`, as shown in the following example: \n\n### GQL\n\n SELECT *\n FROM /employees\n WHERE salary \u003e 100000 AND experience \u003e 0\n ORDER BY salary, experience\n\n### Java\n\n Query\u003cEntity\u003e query =\n Query.newEntityQueryBuilder()\n .setKind(\"employees\")\n .setFilter(\n CompositeFilter.and(\n PropertyFilter.gt(\"salary\", 100000), PropertyFilter.gt(\"experience\", 0)))\n .setOrderBy(OrderBy(\"salary\"), OrderBy(\"experience\"))\n .build();\n\n### Node.js\n\n const query = datastore\n .createQuery(\"employees\")\n .filter(\n and([\n new PropertyFilter(\"salary\", \"\u003e\", 100000),\n new PropertyFilter(\"experience\", \"\u003e\", 0),\n ])\n )\n .order(\"salary\")\n .order(\"experience\");\n\n### Python\n\n query = client.query(kind=\"employees\")\n query.add_filter(\"salary\", \"\u003e\", 100000)\n query.add_filter(\"experience\", \"\u003e\", 0)\n query.order = [\"-salary\", \"-experience\"]\n\nBest practices for optimizing indexes\n-------------------------------------\n\nWhen optimizing indexes, note the following best practices.\n\n#### Order queries by equalities followed by most selective range or inequality field\n\nFirestore in Datastore mode uses the leftmost properties of a composite index to satisfy\nthe equality constraints and the range and inequality constraint, if any, on the\nfirst field of the `orderBy()` query. These constraints can reduce the number of\nindex entries that Firestore in Datastore mode scans. Firestore in Datastore mode uses the remaining\nproperties of the index to satisfy other range and inequality constraints of the\nquery. These constraints don't reduce the number of index entries that\nFirestore in Datastore mode scans, but they filter out unmatched entities so that the number of\nentities that are returned to the clients are reduced.\n\nFor more information about creating efficient indexes, see [index structure and\ndefinition](/datastore/docs/concepts/indexes) and [optimizing indexes](/datastore/docs/concepts/optimize-indexes).\n\n#### Order properties in decreasing order of query constraint selectivity\n\nTo ensure that Firestore in Datastore mode selects the optimal index for your query,\nspecify an `orderBy()` clause that orders range and inequality properties based\non how selective their constraints are in your query, starting from the most\nselective. Higher selectivity matches fewer entities, while lower selectivity\nmatches more entities. In your index ordering, put range and inequality\nproperties with higher selectivity before properties with lower selectivity.\n\nTo minimize the number of entities that Firestore in Datastore mode scans and returns over\nthe network, you should always order properties in the decreasing order of query\nconstraint selectivity. If the result set is not in the required order and the\nresult set is expected to be small, you can implement client-side logic to\nreorder it as per your ordering expectation.\n\nFor example, if you want to search through a collection of employees to\nfind United States employees whose salary is more than $100,000 and order the results by the\nyear of experience of the employee. If you expect that only a small number of\nemployees will have salary higher than $100,000, then an efficient way to\nwrite the query is as follows: \n\n### Java\n\n Query\u003cEntity\u003e query =\n Query.newEntityQueryBuilder()\n .setKind(\"employees\")\n .setFilter(PropertyFilter.gt(\"salary\", 100000))\n .setOrderBy(OrderBy(\"salary\"))\n .build();\n QueryResults\u003cEntity\u003e results = datastore.run(query);\n // Order results by `experience`\n\n### Node.js\n\n const query = datastore\n .createQuery(\"employees\")\n .filter(new PropertyFilter(\"salary\", \"\u003e\", 100000))\n .order(\"salary\");\n const [entities] = await datastore.runQuery(query);\n // Order results by `experience`\n\n### Python\n\n query = client.query(kind=\"employees\")\n query.add_filter(\"salary\", \"\u003e\", 100000)\n query.order = [\"salary\"]\n results = query.fetch()\n // Order results by `experience`\n\nWhile adding an ordering on `experience` to the query will yield the same set\nof entities and obviate re-ordering the results on the clients, the query may\nread many more extraneous index entries than the earlier query. This is because\nFirestore in Datastore mode always prefers an index whose index properties prefix match the\norder by clause of the query. If `experience` were added to the order by clause,\nthen Firestore in Datastore mode will select the `(experience [...], salary [...])` index\nfor computing query results. Since there are no other constraints on\n`experience`, Firestore in Datastore mode will read **all** index entries of the\n`employees` collection before applying the `salary` filter to find the final\nresult set. This means that index entries which don't satisfy the `salary`\nfilter are still read, thus increasing the latency and cost of the query.\n\nPricing\n-------\n\nQueries with range and inequality filters on multiple properties are billed\nbased on entities read and index entries read.\n\nFor detailed information, see the [Pricing](/datastore/docs/pricing) page.\n\nLimitations\n-----------\n\nApart from the [query limitations](/datastore/docs/concepts/queries#limitations_2), note the following limitations before\nusing queries with range and inequality filters on multiple properties:\n\n- To prevent queries from becoming too expensive to run, Firestore in Datastore mode limits the number of range or inequality operators to 10.\n\nWhat's Next\n-----------\n\n- Learn about [optimizing your queries](/datastore/docs/multiple-range-optimize-indexes).\n- Learn more about [performing simple and compound queries](/datastore/docs/concepts/queries).\n- Understand how [Firestore in Datastore mode uses indexes](/datastore/docs/concepts/indexes)."]]