0

I am making an app that get the ingredients than displays the recipes that can be made from those ingredients.The recipes will be stored in fire-base. The structure that i am thinking of going with looks like this:

{
"description" : "Some description",
"name" : "Recipe name",
"idRecipe" : 1,
"ingredients" : {
                 "ingredient1" : "tomato",
                 "ingredient2" : "pepper",
                 .
                 .
                 .
                 "ingredient10": "cheese",
                },
"numOfPersons" : 2,

} 

How can i 'query' the recipes with the matching ingredients,or should the structure be of recipe be changed?

dimalc
  • 23
  • 6
  • In your current data model you can easily find the ingredients for a given recipe. You can't however efficiently query for recipes for a given ingredient. You'll need to create an additional data structure for that. See my explanation here for more: https://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value – Frank van Puffelen Dec 05 '18 at 23:42
  • Alternatively, have a look at Cloud Firestore, which handles such categorization queries more natively, as long as you store them in an array: https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html – Frank van Puffelen Dec 05 '18 at 23:43

1 Answers1

1

You can change your model to like this:

{
"description" : "Some description",
"name" : "Recipe name",
"idRecipe" : 1,
"ingredients" : {
                 "tomato" : true,
                 "pepper" : true,
                 .
                 .
                 .
                 "cheese": true
                },
"numOfPersons" : 2,

}

And then you can use multiple where queries to get this recipe, like:

query = recipeRef.where("ingredients.tomato", "==", true).where("ingredients.pepper", "==", true).where("ingredients.cheese", "==", true);
hkchakladar
  • 749
  • 1
  • 7
  • 15
  • Your query syntax is for Cloud Firestore, but OP is using the Realtime Database. There such queries are not efficiently possible with the current (or your proposed) data structure, since they require that you define an index on each ingredient. See my explanation here for more: https://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value – Frank van Puffelen Dec 05 '18 at 23:39