简体   繁体   中英

Most Efficient Way to Query Firebase iOS

I was working on an app that would use a user's location and execute a web request with their zip code in the URL. This was fairly quick, taking normally 1-3 seconds. I was about to publish the app, but read the terms of use, and was unable to use their service with my app. I have since downloaded a 77k row spreadsheet of zip codes, converted it to JSON, and uploaded it to Firebase. I am currently querying the Firebase in my app to search for the zip code, but it's taking now about 10-15 seconds. My code is as follows:

    func firebaseSearch(zipCode: String) {
    let conditionRef = FIRDatabase.database().reference().child("locations")

    let query = conditionRef.queryOrderedByChild("zip").queryEqualToValue(zipCode)

    query.observeEventType(.Value, withBlock: { snapshot in

        for child in snapshot.children {
            print(child.value["state"])

        }

    })

    }

My firebase is structured as follows:

  • "locations"
    • "1"
      • zip: "12345"
      • state: "XX"
    • "2"
      • zip: "12345"
      • state: "XX"

I have tried to think about how I may structure the Firebase to be more efficient, such as having states be a parent, with children entries inside. I wanted to upload all entries as zip codes; however, my spreadsheet has far too many duplicate codes, and I know firebase doesn't allow duplicates. Is there a more efficient way to query firebase? What if I made the entry number (currently starting from 1 down to 77k) starting at the first zip code, then I queried for a +/- value from the zip code, then filtered those results? My only fear is that looking at the last zip code, the entry number is about 20k off from the actual zip code. I appreciate any tips/suggestions, thank you!

Firebase recommends to avoid nesting data and as far as I can see, yours is well structured, because when you fetch data at a location, it retrieves all its child nodes too. How do you display your data in your app?

Could you maybe make use of pagination to query 25 items at first, then load the next 25, and so on?

query.limitToLast(25).observeEventType(.Value, withBlock: { snapshot in ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM