Reputation: 755
I have below firebase structure:
2014 {
0 {
CityState: "New York, NY",
PinCode: "12345"
},
1 {
CityState: "Los Angeles, CA",
PinCode: "67890"
}
}
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)
}
})
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?
I am using swift 3.2 and Xcode 9.2
Upvotes: 0
Views: 716
Reputation: 599041
Firebase always returns full nodes from the database. There is no API to get a subset of each node.
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"
}
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.
Upvotes: 2