0

I'm trying to fetch child snapshot with childKey of unknown parent without changing Data Structure.

I tried to use queryOrderByChildId with queryEqual(toValue:, childKey:) But my problem is that the child snapshot is dictionary and I know only the key, not the value.

Is there any way to manipulate the value to be Any value, In order that I'll be able to get the child snapshot.

I know title/id1, id3 and id3's timestamp

data structure :

title:
    id1:
         id2:
              id3:
                   timestamp: 101010101
                   visible: true

code:

ref.child("title").child(id1).queryOrderedByKey().queryEqual(toValue: _, childKey: id3)
   .observeSingleEvent(of: .value) { (snapshot) in
      print(snapshot)
}

output value is null

EDIT:

Finally I solved it like that:

ref.child("title").child("id1").queryOrdered(byChild: "id3/timestamp").queryEqual(toValue: 101010101).observeSingleEvent(of: .value) { (snapshot) in
       print("id2 is: ", (snapshot.value as? [String: Any])?.keys.first)
}
Gal
  • 197
  • 1
  • 12

1 Answers1

0

Firebase Database queries work on the direct child nodes of the location you run the query at. There can be only one unknown key in the entire path: the nodes directly under the node you query.

So if you know the title/id1 part of the path, you can query the nodes on level id2 based on their keys, values, or properties at a known path under that (like date/month.

If you know title/id1/id2, you can query the nodes on the id3 level. But you can't query those, if you only know the title/id1 part of their path.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Ok thanks, Let's supposed that I know title/id1, id3 and id3's timestamp, How should my query look like in order to get id3 datasnapshot.value? @frank – Gal Jul 18 '19 at 15:16
  • As said: there can only be one unknown level in the query. If you only know `title/id1`, you're trying to query `title/id1/*/*/timestamp`, which isn't possible. – Frank van Puffelen Jul 18 '19 at 16:50
  • As I mention I know also the **value of id3** and the value of timestamp. Is that helpful ? I know `title/id1/*/id3/timestamp` @frank – Gal Jul 18 '19 at 16:53
  • I don't know only the value of id2 @Frank – Gal Jul 18 '19 at 16:55
  • If `id3/timestamp` is a fixed path you can create an index under `id1` for it, and query that way. But if `id3` is different for many child nodes, it's a categorization problem. In that case check my answer on the second question I linked. Note that's easier to understand what you're trying and how you can accomplish if you don't make the problem abstract with `id1`, `id2` and `id3`, but show the actual values and their meaning. – Frank van Puffelen Jul 18 '19 at 19:21