0

I want to search in firebase by using queryStarting

I have a baseStruct:

products
   Jakets
      red
         name: red
         categoryName: Jakets
   Pants
      blue
         name: blue
         categoryName: Pants
   ...

I tried

let strSearch = "re"
        Database.database().reference().child("products").queryOrdered(byChild:  "name")
            .queryStarting(atValue: strSearch)
            .queryEnding(atValue: strSearch + "\u{f8ff}")
            .observeSingleEvent(of: .value, with: { (snapshot) in

            print("snapshot= \(snapshot)")

        })

In firebase I added rules:

    {
  "rules": {
    ".read": true,
    ".write": true,
    "products": {
      "$someID": {
        ".indexOn": ["name"]
      }
    }
  }
}

But it gives me

snapshot= Snap (products) null

How can I Change my code to search by name?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Andrew0
  • 37
  • 1
  • 8

1 Answers1

0

Firebase Realtime Database queries function on a list of nodes. You execute a query at a certain location, and it returns direct child nodes of that location that have a specific value at a known path.

For example, you can return all jackets that have a name starting with re by doing:

Database.database().reference().child("products/Jakets").queryOrdered(byChild:  "name")
    .queryStarting(atValue: "re")
    .queryEnding(atValue: "re\u{f8ff}")
    .observeSingleEvent(of: .value, with: { (snapshot) in
        ...
    })

But you can't with your current structure perform a query that returns both jackets and pants whose name starts with re. If you want that, you will have to:

  • Either perform separate queries for each product type.
  • Or add an additional data structure that stores all product names in a flat list.

For more on this, see:

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