NetCod NetCod - 5 days ago 4
Swift Question

Firebase and querying for a term in Swift

I am using Firebase for my app and am trying to query the contents of my database. I am using the following query:

DataService.dataService.BASE_REF.child("Posts").
child(selectedComment.commentKey).child("comments").
queryOrderedByChild("userComment").queryEqualToValue(comment).
observeSingleEventOfType(.Value, withBlock: { (snapshot) in


For eg. if I am searching for the term "bose", then only bose shows up, but "Bose", "BOSE" & "Bose XYZ" won't show up. How would I go about querying such that all of the above show up when I query "bose"

Answer

Since you're using queryEqualToValue, you will only get results where the userComment matches exactly with the value you specified.

If you want results where userComments starts with the value, you should use a combination of queryStartingAtValue and queryEndingAtValue:

DataService.dataService.BASE_REF.child("Posts").
    child(selectedComment.commentKey).child("comments").
    queryOrderedByChild("userComment")
    .queryStartingAtValue(comment). queryEndingAtValue(comment+"\uF8FF")
    observeSingleEventOfType(.Value, withBlock: { (snapshot) in

This gives you a range of results, from starting with comment to those starting with comment followed by the last unicode character.

But this still won't match uppercase and lowercase results. If you want that, you will have to store the data in a uniform case to enable searching. The Firebase Database is more focused on realtime data synchronization than on completeness of its (text) search capabilities.

Also see: