0
{
  "Events" : {
    "16" : { 
      "eventDate" : "2021-02-02",
      "eventId" : "16",
      "eventName" : "First Test",
      "eventTime" : "09:39:00"
    },
    "22" : {
      "eventDate" : "2021-02-02",
      "eventId" : "22",
      "eventName" : "Test22 Exam",
      "eventTime" : "09:39:00"
    },
    "26" : {
      "eventDate" : "2021-02-02",
      "eventId" : "26",
      "eventName" : "Webinar",
      "eventTime" : "09:39:00"
    }
  }
}

If I'm storing my Events like this, and I want to get the node where EventId is equal to 16 and 26. How can I do that?

The above is the child of issue, which is a child of root.

I Tried with equalTo but get only single record. I need to get 16 and 26 both.

DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Events").orderByChild("eventId").equalTo("16"); 
Jigar Patel
  • 1,550
  • 2
  • 13
  • 29
  • Please check the duplicate to see how you can achieve this. You might also try using [Cloud Firestore](https://firebase.google.com/docs/firestore/query-data/queries#simple_queries). – Alex Mamo Feb 03 '21 at 12:53
  • 1
    @AlexMamo: I actually don't think this is a duplicate of the question you marked, as here OP is trying to do an OR of multiple values, not an AND across multiple properties. Using Firestore is a valid option for this type of query though. – Frank van Puffelen Feb 03 '21 at 14:50
  • @FrankvanPuffelen Even if the OP wrote "16 and 26", yes, it's an OR rather than an AND. Btw, so happy to see DatabaseReference#get() and Query#get(), added in the Firebase Realtime Database SDK December's update. Thank you. – Alex Mamo Feb 03 '21 at 15:13
  • 1
    Yeah, `get()` slipped into the Android SDKs a bit earlier than expected, so we're still catching up with doc and a blog post. More small improvements to the RTDB SDKs are coming up. – Frank van Puffelen Feb 03 '21 at 15:15
  • @FrankvanPuffelen Can't wait to see them :) – Alex Mamo Feb 03 '21 at 15:25

1 Answers1

1

Firebase doesn't support ORs in its queries. The only way to get multiple nodes based on the values of a specific property would be to use a startAt and endAt to select a range of values, but in your case that would also return the node with eventId equal to 22.

Given that the keys of the nodes are the same as your eventId properties, the fastest way I can think of to retrieve multiple nodes is by using a separate addListenerForSingleValueEvent() or get() call for each key:

reference.child("Events").child("16").get(...)
reference.child("Events").child("26").get(...)

Retrieving multiple child nodes like this is quite fast in Firebase, as all requests are sent over a single, existing socket connection. For more on this, see Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807