我想从每个用户名值中搜索我的用户群。据我所见,网上人们经常返回所有 用户,然后在表格 View 中过滤他们,但这似乎不切实际也不可行。我的想法是查询数据并返回一个呈指数级变小的值数组,但我在使用提供的查询方法时遇到了问题。
如何查询数据库的特定方面?
我如何构建我的代码以使其可行;不会在每个用户中加载,一次最多加载 10 个。
非常感谢任何建议、资源和链接。
编辑:
我做了一些研究,看起来 Firebase 带有一些内置的查询方法......到目前为止,这就是我试图用下面的代码测试它以打印出以 I 开头的用户,但我可以'让它打印控制台中的任何用户
ref.queryOrderedByKey().queryStarting(atValue: "I").queryEnding(atValue: "I\u{f8ff}")
.observe(.childAdded, with: { snapshot in
print(snapshot.key)
})
最佳答案
有很多解决方案,而且通常加载所有用户数据会导致数据过多。
这是一个典型的用户节点
users
uid_0
name: "Jean Luc"
uid_1
name: "Will"
uid_2
name: "Geordi"
一种选择是遍历每个用户节点,一次一个,以检索用户名。这完全避免了庞大的数据集。我们将使用 .childAdded 事件加载每个事件并将其存储在数组中
let usersRef = self.ref.child("users")
var userNamesArray = [String]()
usersRef.observe(.childAdded, with: { snapshot in
let userDict = snapshot.value as! [String: Any]
let name = userDict["name"] as! String
userNamesArray.append(name)
})
第二种选择是将用户名存储在一个完全不同的节点中,这会显着减少“困惑”,因为其余数据仍保留在主用户节点中
user_names
uid_0: "Jean Luc"
uid_1: "Will"
uid_2: "Geordi"
正如您在这个结构中看到的,即使有数千个名字,它也只是占地面积非常小的文本。
另一种选择是使用 .startingAt 和 .endingAt 一次加载 X 数量的用户,并迭代返回的用户以获取每个名称。在这种情况下,我们希望所有用户都以 A 开头并以 M 结尾...抱歉,Worf。
let usersRef = self.ref.child("users")
var userNamesArray = [String]()
let nameQuery = usersRef.queryOrdered(byChild: "name")
.queryStarting(atValue: "A")
.queryEnding(atValue: "M\u{f8ff}")
nameQuery.observe(.value, with: { snapshot in
for child in snapshot.children {
let snap = child as! DataSnapshot
let userDict = snap.value as! [String: Any]
let name = userDict["name"] as! String
userNamesArray.append(name)
}
})
最后一个例子,用户名以A开头,用户名以M结尾+一个非常高的unicode字符,这使得它包含所有以M开头的用户名
The \uf8ff character used in the query above is a very high code point in the Unicode range. Because it is after most regular characters in Unicode, the query matches all values that start with queryString.
关于ios - 有效地查询火力地堡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45132981/