Home > Net >  swift firebase queryStartingAtValue
swift firebase queryStartingAtValue

Time:12-03

I'm new to firebase and am trying to search the title of the product using queryStartingAtValue. in my firebase JSON and code below, I have a few levels to travel. it look like -> /item/(section name: clothing,games etc)/autoID/(product name, price) I was able to receive the results using for-loops all the way down until finding the specific string but it doesn't look good. I was wondering if queryStartingAtValue can shorten the trips looping through a child within the child or at least how to properly use queryStartingAtValue much appreciated for help!! thanks

SWIFT

Database.database().reference().child("item").queryStarting(atValue:"Adidas").observeSingleEvent(of: .value) { (snapshot) in
            
            for snap in snapshot.children {
                if let snap = snap as? DataSnapshot {
                    if let childItem = snap.value! as? [String: Any] {
                        for key in childItem {
                           if let item = key.value as? [String: Any] {
                             if let title = item["Title"] as? String {
                               if title.contains("adidas") {
                                   print("found")
                               }
                             }
                           } 
                        }   
                    }
                }
            }
        }

Firebase JSON

{
  "item": {
    "Clothing": {
      "-NFrGoNiI4zX-QBgEwkf": {
        "Price": 345,
        "Title": "Adidas",
        "availableQty": "100"
      }
    },
    "Games": {
      "-NFrGdmdV4FOBI34EnOW": {
        "Price": 199,
        "Title": "Overwatch Platinum Pack",
        "availableQty": "100"
      },
      "-NGL4vk1GC80ojMgZNik": {
        "Price": 66,
        "Title": "Overwatch 2",
        "availableQty": "100"
      }
    }
  }
}

CodePudding user response:

if you need to powerfull search engine for firebase-ecommerce-app, you can use Algolia

  1. Take a free plan to algolia

  2. Algolia with firebase cloud-function (very easy!) article algolia and cloud function

  3. Algolia with swift algolia-swift

CodePudding user response:

Firebase Realtime Database queries consist of two steps:

  1. First you order the child nodes on their key, their value or a child property.
  2. Then you take a slice of that data by using startAt/endAt/startAfter/endAfter/equalTo.

Your code contains #2, but it does not contain any ordering instruction, which means that the database orders the nodes on their keys.

You'll instead want to include an instruction to order on the Title child property:

Database.database().reference()
  .child("item")
  .queryOrdered(byChild: "Title") //            
  • Related