Why does query firestore not return the expected result using order 2 times

37 Views Asked by At

While composing a composite query for firebase, I ran into a problem.

I use geoHash filtering as specified in the documentation https://firebase.google.com/docs/firestore/solutions/geoqueries?hl=en&%3Bauthuser=0&authuser=0 And besides that, I want to use other sorting criteria of the format ">=" or "<=".

Also in the documentation it is written that when using the operator ">=" or "<=", it is necessary to set order by this property

When I compose a query with my parameters, it returns an empty array.

The request looks like this:

query(
    collection(db, '/some'),
    where('some', '==', arg),
    where('some another', '==', arg),
    where('some another', 'array-contains-any', arg),
    where('price', '>=', minPrice),
    orderBy('price'),
    orderBy('geoHash'),
    startAt(b[0]),
    endAt(b[1]),
    limit(Math.ceil(DEFAULT_LIMIT_OF_LISTINGS - promises.length))
)

When we add filtering by price and sort by price, the query returns nothing.

I was checking my query by dividing it into 2 different ones. Everything worked. There are no problems in my data either. There are also no errors from firebase in the console

1

There are 1 best solutions below

1
NZWEB On

Firestore queries can only contain one relational condition (>=, >, etc) because such conditions can only be evaluated on the first field in an index. Since you need a relational/range condition for the geohash already, you can't also have a >= condition on price.

The common options to work around this are:

Perform the filter on the second condition in your application code, so that you first get all documents that are in range, and then in your application remove the ones whose price is out of range. Add a field to your database that allows the use-case you want. For example, if you add a field isPriceOver4000: true you can use an equality condition .where('isPriceOver4000', '==', true). That last option may feel wrong, but is actually quite common when using NoSQL to modify and augment your data model to fit with your use-case. Of course you'll want to find the best model for your needs, for example you might want an array (or map subfield) of price tags that users can filter on.

Alternatively, you can create similar buckets of regions, and query the location on that instead of geohash, and then use the >= on price.