Search code examples
firebasefirebase-realtime-database

query a keyword in Firebase database


Support I have a database like below:

{
  "eventAttendees" : {
    "fm" : {
      "9" : "Alice",
      "23" : "Khanh",
      "43" : "Bach"
    }
  },
  "events" : {
    "fm" : {
      "date" : "2017-06-16",
      "name" : "I love Firebase Meetup in Tokyo yesterday". 
    },
    "gm" : {
      "date" : "2017-08-12",
      "name" : "Meet Linh"
    }
  },
  "users" : {
    "1" : {
      "name" : "David"
    },
    "2" : {
      "name" : "Alice"
    },
    "10" : {
      "name" : "Khanh"
    }
  }
}

If I query the keyword "Firebase Meetup", it works.

let query = ref.child("events").queryOrdered(byChild: "name").queryEqual(toValue: "Firebase Meetup").queryLimited(toFirst: 1)
        query.observe(.value, with: { (snapshot) in
             let content = snapshot.value as? [String : AnyObject] ?? [:]
            print(content)

-> Return

["fm": {
    date = "2017-06-16";
    "name" : "I love Firebase Meetup in Tokyo yesterday". ;
}]

but if I query the keyword "Firebase", it does not work.

If it possible to query "Firebase" and get result like below?

 ["fm": {
            date = "2017-06-16";
            "name" : "I love Firebase Meetup in Tokyo yesterday". ;
        }]

Solution

  • you can use the startAt() function:

    let query = ref.child("events").queryOrdered(byChild: "name").queryStart(at: "I love Firebase").queryLimited(toFirst: 1)
            query.observe(.value, with: { (snapshot) in
                 let content = snapshot.value as? [String : AnyObject] ?? [:]
                print(content)
    

    Documentation here https://firebase.google.com/docs/reference/js/firebase.database.Query#startAt

    In addition, if you want start with Firebase or ending with Meetup, just do:

    let query = ref.child("events").queryOrdered(byChild: "name").queryStart(at: "Firebase").queryEnd(at: "in Tokyo yesterday").queryLimited(toFirst: 1)
            query.observe(.value, with: { (snapshot) in
                 let content = snapshot.value as? [String : AnyObject] ?? [:]
                print(content)
    

    Documentation here https://firebase.google.com/docs/reference/js/firebase.database.Query#startAt