Shubham Sardar
Shubham Sardar

Reputation: 101

How can I build a firestore query for Android with whereGreaterthan() filters for two different fields?

I need to filter the list of my documents which I am fetching from firestore in my android app. this is the query.

  query = FirebaseFirestore.getInstance()
            .collection("students")
            .whereLessThan("mAge",25)
            .whereGreaterThan("mAge",20)
            .whereGreaterThan("mGrades",20);

but, I get an error in the log:

java.lang.RuntimeException: Unable to start activity ComponentInfo{dsardy.in.acchebacche/dsardy.in.acchebacche.MainActivity}: java.lang.IllegalArgumentException: All where filters other than whereEqualTo() must be on the same field. But you have filters on 'mAge' and 'mGrades'

Can this be achieved? a filter with two or more fields greater than some values is an important and general query, firestore must have something to tackle this.

Upvotes: 3

Views: 2431

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

Edit: 2024/04/18

As @FrankvanPuffelen mentioned in his comment:

Firestore recently added the ability to have inequality and range conditions on multiple fields in a single query.

Below are docs:


Firestore allows to chain of multiple inequality conditions to create more specific queries, but only on the same field. As you can probably see in the official documentation range filters on different fields are forbidden.

To achieve what you want, you need to query your database twice, once to filter data using .whereGreaterThan("mAge",20) and second using .whereGreaterThan("mGrades",20) but you cannot use them in the same query.

Another way to make it happen is to store a special field that might fit the query, although in real-world applications it will be almost impossible to store every single way a user might query the data.

Upvotes: 4

Related Questions