taeseok ki
taeseok ki

Reputation: 143

Cloud Firestore : Is compound range query in more than 2 fields available now?

I need to get ranged data like this.

ex) 10 < a < 20 ,  30 < b < 40

a and b both fields are index key now.

I think in this situation compound range query is the easy way.

But in Cloud Firestore, range queries are possible only for one field.

ex)   (possible) citiesRef.where("state", "==", "CA").where("population", "<", 1000000)

    (impossible) citiesRef.where("state", ">=", "CA").where("population", ">", 100000)

How can I range query in 2 fields?

Upvotes: 3

Views: 1035

Answers (2)

Louis Kuang
Louis Kuang

Reputation: 797

As of 2024-04-12, Firestore now supports range & inequality filters on multiple fields. Please read the documentation for details.

Upvotes: 1

Dan McGrath
Dan McGrath

Reputation: 42046

As writing, this is not possible with Cloud Firestore and will likely never be available. Depending on your requirements though, there are workarounds by rethinking your data model and queries slightly.

Option 1: Precompute a range

In this option you can add a field called population_bracket. In here, you essentially place the population value into a bracket you can test. Either decide by hand what the ranges are depending on your need, or use some automated method like ceil(log(population))

As an example the population of CA is roughly 39250000, so using the log method ceil(log(population)) we get 8 which is what we'd store in population_bracket. If we're okay with the population range filter being changed to <= 1000000, then we can make the population filter a simple equality check using population_bracket == 6. CA gets correctly excluded!

Option 2: client-side filter

In this option you make an educated guess which range filter will reduce the resultset the most, then simply do client-side filter of the results for the second filter (e.g, just ignore every state < "CA")

Upvotes: 2

Related Questions