-1

I'd like to fetch snapshot which contains typed text. For example node look like this

"Team": {
 "Yankees": {
    "uid1": "name",
    "uid2": "name"
   },
"Angels": {
   "uid1": "name"
   "uid3": "name"
 }

and if user typed yan in search bar then I want to fetch "Yankees" snapshot. I saw some document and stack over flow post and tried like so

ref.child("Team").queryStarting(atValue: "yan").queryEnding(atValue: "yan\u{f8ff}").observe

but it doesn't work. How can I do this? Thank you!

Daibaku
  • 11,416
  • 22
  • 71
  • 108

2 Answers2

1

Firebase searches are case sensitive. Since your key starts with an uppercase Y, the query only matches if it also does that:

ref.child("Team")
   .queryOrderedByKey()
   .queryStarting(atValue: "Yan")
   .queryEnding(atValue: "Yan\u{f8ff}").observe

I also queryOrderedByKey() to be explicit about what you want to order/filter on.

If you want to allow case-insensitive filtering, the typical approach is to add a property with the all-lowercase value to each team:

"Team": {
 "Yankees": {
    "teamNameForSearch": "yankees",
    "uid1": "name",
    "uid2": "name"
   },
"Angels": {
    "teamNameForSearch": "angels",
   "uid1": "name"
   "uid3": "name"
 }

Now you can search with:

ref.child("Team")
   .queryOrdered(byChild: "teamNameForSearch")
   .queryStarting(atValue: "yan")
   .queryEnding(atValue: "yan\u{f8ff}").observe

A final note is that both approaches only do so-called prefix matches: they find teams whose name starts with what the user typed. If you want a contains operation (as the title of your question suggests), you will have to look beyond Firebase for a solution. For more on that, see Kato's answer here: Firebase query - Find item with child that contains string

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

You need to change the db to this:

"Team": {
"randomid": {
"team":"Yankees",
"uid1": "name",
"uid2": "name"
},
"randomid": {
 "team":"Angels"
 "uid1": "name"
 "uid3": "name"
}

and now you can do this:

ref.child("Team").queryOrdered(byChild: "team").queryStarting(atValue: "Yan").queryEnding(atValue: "Yan\u{f8ff}").observe

First in your query above, you need to use queryOrdered() to know which child you want to order.

Also in your database the node Team is not equal to anything, it is a parent node that has child nodes.

So to fix this, the node Team needs to be equal to a value(like in the database in this answer) so you will be able to order it and use queryStarting and queryEnding on it.

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134