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"
}
}
}
}
2
Answers
if you need to powerfull search engine for firebase-ecommerce-app, you can use Algolia
Take a free plan to algolia
Algolia with firebase cloud-function (very easy!)
article algolia and cloud function
Algolia with swift
algolia-swift
Firebase Realtime Database queries consist of two steps:
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: