Dr_Mom
Dr_Mom

Reputation: 63

Firebase search through data keyword

I have Firebase entity like this:

firebase entity

This func show me all my data:

    func getRecipes(text: String, completion: @escaping (Recipe) -> Void)
    {
    let databaseRef = FIRDatabase.database().reference()
    databaseRef.child("Recipes").queryOrdered(byChild: text).observe(.childAdded, with: { snapshot in
      if let value = snapshot.value as? [String : AnyObject] {
        let recipe = Recipe(dictionary: value)
        completion(recipe)
      }
    }) { (error) in
            print(error.localizedDescription)
    }

I need only to show data, which have in its name "text" (i.e. "Beer" or "Pie").

Upvotes: 0

Views: 1742

Answers (1)

user3476154
user3476154

Reputation:

In queryOrdered(byChild: text) the (byChild' stands for the child node (property) you want to search on, which in this case would be 'title'. Then you want to specify what you're searching for. You can do this by using queryEqual(toValue: text)

So databaseRef.child("Recipes").queryOrdered(byChild: text) would become databaseRef.child("Recipes").queryOrdered(byChild: "title").queryEqual(toValue: text)

However, this won't work in your case since you're searching for a certain substring instead of a matching string, which is comparable to a LIKE operation in SQL. Firebase currently doesn't allow this. The only similar thing that would be possible is searching for a string that starts with a certain substring.

If you're trying to filter on a certain category you'd be better off adding a 'category' node and searching for a specific value. Or, if you're trying to implement a search function you would probably have to use a search API. I've heard a lot of Elasticsearch but never worked with it so you should do some research.

Upvotes: 1

Related Questions