Filtered searches with Firebase?

2020-07-27 06:11发布

问题:

I'm looking to have a searchbar where a user can search through users on Firebase and have a tableview updating as they type instead of just searching for exact matches.

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    if searchBar.text == nil || searchBar.text == "" {
        inSearchMode = false
        tableView.reloadData()  
    } else {
        inSearchMode = true
        let lower = searchBar.text!.lowercaseString

        filteredPeopleArray = peopleArray.filter({$0.title.hasPrefix(lower) != nil})
        tableView.reloadData()
}

This code works for that, but what this would require is on load for me to fill an array with every single user currently on firebase and to constantly be appending new users as they're being created while the app is open.

I see that parse used to have a "find users where key contains string" and you would do a query to parse in your textDidChange, but I'm not seeing anything like that for Firebase. Also, would that not be taxing on data in any way to send a query to firebase every time a letter is typed in?

What method is used by like Instagram for example where you type in some letters and return back a list of users from a server with that prefix in their name? So like "Bo" might return a list of bobs and bobbys.

回答1:

I am not able to comment, but here's an article that helped me.

https://www.quora.com/How-would-you-search-a-Firebase-Realtime-Database-with-a-substring

Let say you have below firebase data

{
  "lambeosaurus": {
    "dimensions": {
      "height" : 2.1,
      "length" : 12.5,
      "weight": 5000
    }
  },
  "stegosaurus": {
    "dimensions": {
      "height" : 4,
      "length" : 9,
      "weight" : 2500
    }
  }
}

The below example finds all dinosaurs whose name starts with the letter "b".

var ref = new Firebase("https://example.firebaseio.com/");
ref.orderByKey().startAt("b").endAt("b\uf8ff").on("child_added", function(snapshot) {
  console.log(snapshot.key());
});