Query with range and inequality filters on multiple properties overview
Stay organized with collections
Save and categorize content based on your preferences.
Firestore 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
your application development by delegating implementation of post-filtering
logic to Firestore in Datastore mode.
Range and inequality filters on multiple properties
The following query uses range filters on priority and days to return all tasks
with priority greater than four and with less than three days to complete.
Before you start running queries, make sure you have read
about queries.
If an ORDER BY clause isn't specified, Firestore in Datastore mode uses any index that
can satisfy the query's filter condition to serve the query. This approach produces a result
set that is ordered according to the index definition.
To optimize the performance and cost of Firestore in Datastore mode queries,
optimize the order of properties in the index. To do this, ensure that your
index is ordered from left to right so that the query distills to a
dataset that prevents scanning of extraneous index entries.
For example, suppose you want to search through a collection of employees to
find United States employees whose salary is more than $100,000 and whose number
of years of experience is greater than 0. Based on your understanding of the
dataset, you know that the salary constraint is more selective than the
experience constraint. An index that reduces the number of index scans is the
(salary [...], experience [...]) index. As a result, a fast and cost-efficient
query orders salary before experience, as shown in the following example:
When optimizing indexes, note the following best practices.
Order queries by equalities followed by most selective range or inequality field
Firestore in Datastore mode uses the leftmost properties of a composite index to satisfy
the equality constraints and the range and inequality constraint, if any, on the
first field of the orderBy() query. These constraints can reduce the number of
index entries that Firestore in Datastore mode scans. Firestore in Datastore mode uses the remaining
properties of the index to satisfy other range and inequality constraints of the
query. These constraints don't reduce the number of index entries that
Firestore in Datastore mode scans, but they filter out unmatched entities so that the number of
entities that are returned to the clients are reduced.
Order properties in decreasing order of query constraint selectivity
To ensure that Firestore in Datastore mode selects the optimal index for your query,
specify an orderBy() clause that orders range and inequality properties based
on how selective their constraints are in your query, starting from the most
selective. Higher selectivity matches fewer entities, while lower selectivity
matches more entities. In your index ordering, put range and inequality
properties with higher selectivity before properties with lower selectivity.
To minimize the number of entities that Firestore in Datastore mode scans and returns over
the network, you should always order properties in the decreasing order of query
constraint selectivity. If the result set is not in the required order and the
result set is expected to be small, you can implement client-side logic to
reorder it as per your ordering expectation.
For example, if you want to search through a collection of employees to
find United States employees whose salary is more than $100,000 and order the results by the
year of experience of the employee. If you expect that only a small number of
employees will have salary higher than $100,000, then an efficient way to
write the query is as follows:
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`
While adding an ordering on experience to the query will yield the same set
of entities and obviate re-ordering the results on the clients, the query may
read many more extraneous index entries than the earlier query. This is because
Firestore in Datastore mode always prefers an index whose index properties prefix match the
order by clause of the query. If experience were added to the order by clause,
then Firestore in Datastore mode will select the (experience [...], salary [...]) index
for computing query results. Since there are no other constraints on
experience, Firestore in Datastore mode will read all index entries of the
employees collection before applying the salary filter to find the final
result set. This means that index entries which don't satisfy the salary
filter are still read, thus increasing the latency and cost of the query.
Pricing
Queries with range and inequality filters on multiple properties are billed
based on entities read and index entries read.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-28 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)."]]