Florian Walther
Florian Walther

Reputation: 6961

Firestore compound query with map fields

In my chat application, I store the participants of a chat as their UIDs in a Map so I can so I can do queries like this:

.whereEqualTo("participantUIDs.$currentUserUid", true)
.whereEqualTo("participantUIDs.$partnerUid", true)

The problem is when I try to use this with orderBy

.whereEqualTo("participantUIDs.$currentUserUid", true)
.orderBy("lastMessageSentTimestamp")

I have to create a custom index. But this index will contain that specific user UID and I can't create an index for every user in my app. How can I circumvent this problem?

Upvotes: 0

Views: 180

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

Regarding:

I can't create an index for every user in my app.

That's definitely not an option, as there are some limitations when it comes to Cloud Firestore indexes:

However, even if you manage to stay below these limits, that's not an option to manually create an index for each and every user that joins your app.

In my opinion, for your particular use-case, you should consider augmenting your data structure to allow a reverse lookup. Meaning that you should create a participantUIDs collection where you should keep the lists for each user. This technique is called denormalization and is a common practice when it comes to NoSQL databases like Cloud Firestore or Firebase Realtime Database.

But remember, there is "no perfect database structure":

It's a little old, but I think this video might also help:

More info regarding why you need an index:

P.S. You can also rely on Firebase Realtime Database when Cloud Firestore may become a little expensive. Both work really well together.

Info:

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317467

You can order the documents on the client after an unordered query. This should not be very taxing on the client app when the number of documents is less than 10,000.

Upvotes: 1

Related Questions