Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore order by two fields

In firestore I'm wondering if there is a way to have a hueristic1 and get all data between two hueristic1 values but order the results based on a hueristic2.

I ask because the data at bottom of both pages

https://firebase.google.com/docs/firestore/query-data/order-limit-data

https://firebase.google.com/docs/firestore/query-data/query-cursors

there seems to be slightly contradictory documentation.

What I want to be able to do is

Ref.startAt(some h1 value).endAt(some second h1 value).orderBy(h2).  

I know I'd probably have to index by h1 but even then I'm not sure if there is a way to do this.

like image 707
Blue Avatar asked Nov 19 '17 20:11

Blue


1 Answers

Update:

I didn't test this well enough to see that is doesn't produce the desired ordering. The OP asked the question again and got an answer from a Firebase team member:

Because Cloud Firestore doesn't support ordering by a different field than the supplied inequality, you won't be able to sort by name directly from the query. Instead you'd need to sort client-side once you've fetched the data.


The API supports the capability you want, although I don't see an example in the documentation that shows it.

The ordering of the query terms is important. Suppose you have a collection of cities and the fields of interest are population (h1) and name (h2). To get the cities with population in range 1000 to 2000, ordered by name, the query would be:

citiesRef.orderBy("population").orderBy("name").startAt(1000).endAt(2000)

This query requires a composite index, which you can create manually in the console. Or as the documentation there indicates, the system will help you:

Instead of defining a composite index manually, run your query in your app code to get a link for generating the required index.

like image 102
Bob Snyder Avatar answered Sep 18 '22 13:09

Bob Snyder