从Firebase检索键的特定值的列表 [英] Retrieve list of a particular value for a key from Firebase
问题描述
我具有以下firebase结构:
I have below firebase structure:
2014 {
0 {
CityState: "New York, NY",
PinCode: "12345"
},
1 {
CityState: "Los Angeles, CA",
PinCode: "67890"
}
}
我必须从firebase数据库中获取所有CityState字段的列表. 但是我总是获取完整的数据,然后不得不像下面这样过滤数据:
I have to get list of all the CityState field from the firebase database. But I always get full data and then have to filter the data like below:
ref?.child("2014").observeSingleEvent(of: .value, with: { snapshot in
if let item = snapshot.value as? [Dictionary<String, Any>] {
for items in item {
print(items["CityState"])
}
} else {
print (snapshot.value)
}
})
由于要检索的海量数据,时间太长.是否有一个firebase查询,我可以从中获取"CityState"键的值列表?
It takes too long time because of huge data to be retrieved. Is there a firebase query where I can get list of values of "CityState" key?
我正在使用Swift 3.2和Xcode 9.2
I am using swift 3.2 and Xcode 9.2
推荐答案
Firebase始终从数据库返回完整的节点.没有API可以获取每个节点的子集.
Firebase always returns full nodes from the database. There is no API to get a subset of each node.
在使用Firebase数据库(和大多数其他NoSQL数据库)时,建议对应用程序用例的数据进行建模.因此,如果您需要在应用程序中显示城市州列表,则可能应该在数据库中存储城市州列表:
When using the Firebase Database (and most other NoSQL databases) it is recommended to model the data for the use-cases of your app. So if you need to show a list of city states in your app, you should probably store a list of city states in your database:
CityStates: {
0: "New York, NY",
1: "Los Angeles, CA"
}
如果您只想显示特定年份的城市,可能还需要按年份存储它们(就像您的原始JSON一样):
If you want to show the city states for only a specific year, it might be worth also storing them by year (as your original JSON does):
CityStates: {
2014 {
0: "New York, NY",
1: "Los Angeles, CA"
}
}
有了这些结构,从您的应用程序中读取数据变得微不足道,并且您读取的数据不超过您需要在应用程序中显示的数据.
With these structures, reading the data from your app becomes trivial and you're reading no more data than what you need to display in your app.
注意:以上结构以类似数组的结构存储城市状态.如果顺序不重要,请考虑将它们存储在类似集合的结构中:
Note: The above structure stores the city states in an array-like structure. If the order is not important, consider storing them in a set-like structure:
CityStates: {
2014 {
"Los Angeles, CA": true,
"New York, NY": true
}
}
此结构的优点是不会有任何重复项,因为根据定义,键在父节点中保证是唯一的.
The advantage of this structure is that there can't be any duplicates, since keys are by definition guaranteed to be unique within a parent node.
这篇关于从Firebase检索键的特定值的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!