'Firebase Database Issue in searching users by username initials and returning all users three
this is the way i store my data on Firebase DB:
USERS : {
UUID : {
username : "a"
}
UUID :{
username : "b"
}
I have already Indexed the username on rules. And this is the query for trying to retrieve data:
var dbRef = Database
.database(url:"http//servername").reference(withPath: "users")
//
dbRef.queryOrdered(byChild: "username").queryStarting(atValue: initials, childKey: "username")
.observeSingleEvent(of: .value) { datasnap in
var a = datasnap.value
var b = a as! [String : Any]
b.forEach { key, value in
var a = value as! [String : Any]
print(a["username"] as! String)
}
The problem that I have is :
- when I retrieve the dataSnapshot I have all the child three and not just the username
- the query results different strange values no matter of the initials
Does anybody have any solution or idea please, for actually searching usernames by their initials and not receiving random results(and also no case sensisitive).
There are two answers on stack for simmilar questions but are over 5-10 years ago and doesnt work. Thank you everybody,
Solution 1:[1]
This challenge is like knowhow - searching objects with string key for searching data on the firestore.
let startTxt: String = searchKey
let endTxt: String = searchKey + "\u{f8ff}"
FUSER_REF
.whereField(User.key_uname, isGreaterThanOrEqualTo: startTxt)
.whereField(User.key_uname, isLessThanOrEqualTo: endTxt)
.limit(to: count)
.getDocuments{ (doc, err) in ....
Let me know if that works for you! :)
That would be good if you save lowercased usernames on the datatabase. And then search the usernames with this updated start/end text.
let startTxt: String = text.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
let endTxt: String = (text + "\u{f8ff}").lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
This was working well with 700k users database.
Solution 2:[2]
I needed to use .queryStarting(afterValue: initials, instead of atValue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Frank van Puffelen |
