1

This is my database design.

foodie-ab2b4{
 Foods{
   0{
    FoodName: "Baked Beans In Tomato Sauce"
    FoodRecipe: 
    FoodUri: 
    Image: 
    }
   1{
    FoodName: "Another bean | Bubbling Bacon Butter Beans recipes"
    FoodRecipe: 
    FoodUri: 
    Image: 
    }
   }
  }

I'm working on an ios project and this is how my firebase json structured.

let ref = Database.database().reference()
func searchFoodByName(FoodName: String){
    let foodsRef = ref.child("Foods")

    let input = FoodName
    let query = foodsRef.child(key).queryOrdered(byChild: "FoodName").queryEnding(atValue: input)
    query.observeSingleEvent(of: .value, with: { snapshot in
        print(snapshot)
        for child in snapshot.children {
            let snap = child as! DataSnapshot
            let dict = snap.value as! [String: Any]
            let fName = dict["FoodName"] as! String
            let fIngredients = dict["Ingredients"] as! [String]
            print(fName)
            print(fIngredients)

            let key = snapshot.key
            print(key)
        }
    })    
}

I'm trying to filter my food objects by their names. I have 10 objects in my database. In most cases this search return true objects. But there is one example i can not solve.

When i query the "tomato" word i need to get 1 object. But there is two. Although there is no tomato word in my second object.

The two object is in my json file.

If it is necessary i can upload my whole JSON file to here.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Asgencer
  • 41
  • 3

1 Answers1

0

You seem to assume that Firebase can filter based on strings that contain a value, but it can't. See Firebase query - Find item with child that contains string (and the many links from there).

What Firebase can do is search for string values that start with a certain value. You do that by using a combination of queryStarting(atValue:) and queryEnding(atValue:):

let query = foodsRef
  .queryOrdered(byChild: "FoodName")
  .queryStarting(atValue: input)
  .queryEnding(atValue: input+"\\uf8ff")

If you use this query, and input is ``Baked`, it will only match the first food from your JSON.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807