Reputation: 13
I have a database in firebase which sort of looks like this:
-Messages
-randomGenKey
-receiverUid:string1
-senderUid:string2
I am trying to search if string1 and string2 are a specific value lets say "user1" and "user2", respectively. I am unsure of how I can accomplish this. I know I can get to Messages by simply doing
mMessagesRef = FirebaseDatabase.getInstance().getReference().child("messages");
But get stuck after that because randomGenKey is unknown when I am searching.
Upvotes: 1
Views: 445
Reputation: 599776
As @creativecreatorormaybenot said, you can you a query to filter on either senderUid
or receiverUid
. But a Firebase Database query can only filter on one property, so you cannot use it to filter on both properties. You may be able to combine the two values into a single property and filter on that. For more into on this and other ways to filter, see my answer here: http://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase
But since it seems like you're creating a messaging application, I'd also consider an alternative data structure. If your users are having 1:1 conversations, I'd recommend looking at a data structure that models each conversation as a node in the tree. So instead of having one long list of messages between all of the users of your app (very much a SQL model), model it as multiple (much smaller) conversations:
-Messages
-keyOfRoomOne
-message1
-message2
-keyOfRoom2
-message1
-message2
And then also keep a list of all the rooms for each user:
-Users
-Uid1
-keyOfRoomOne
-keyOfRoomTwo
-Uid2
-keyOfRoomOne
-Uid3
-keyOfRoomTwo
With this structure you look up the room ID when the chat starts, which is much less frequently than for each message.
Alternatively you can use a room name that reflects the users in it and not even need the lookup. For more on that, see http://stackoverflow.com/questions/33540479/best-way-to-manage-chat-channels-in-firebase
Upvotes: 2
Reputation: 126894
FirebaseDatabase.getInstance().getReference("messages").orderByChild("receiverUid").equalTo("user1")
You cannot use two queries, so this is as far as you get. You will be able to check if senderUid
equals user2
on the client side by going through all the result objects. Find more on this here.
Upvotes: 1