0

It's easier to explain through an example.

The data in question is:

data : { 

cluster1 : { 
id: 123 
things: [153, 525, 743] 
},

cluster2 : { 
id: 124 
things: [113, 547, 124] 
},

}

And we want to find all clusters that have things containing '547', which case should return the whole of cluster2.

I know how to do this in firestore, it would look something like this:

  db.collection("data")
        .where("things", "array-contains", userInput)

But for certain reasons I can't use firestore.

Does anyone know if there is a way to do it in Firebase Realtime Database.

Thank you!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

1 Answers1

0

There is no equivalent to Firestore's array-contains in the Realtime Database API. The closest you can get is to store the data as a map, with true as their value:

data : { 
  cluster1 : { 
    id: 123 
    things: {
      "153": true, 
      "525": true,
      "743": true
    } 
  },
  cluster2 : { 
    id: 124 
    things: {
      "113": true, 
      "547": true, 
      "124": true
    } 
  },
}

Now you can define an index on each property in things, and then use that in your query: ref.orderByChild("things/113").equalTo(true).


Since the values in your things array are likely dynamic and not predefined, you won't be able to defined indexes for them. In that case you'll need to add an inverted data structure, that maps thing IDs back to clusters.

For an example of this, see Firebase query if child of child contains a value

For more on this topic, also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807