0

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!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
SF Dev
  • 389
  • 1
  • 3
  • 13

1 Answers1

0

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 ...
waseefakhtar
  • 1,373
  • 2
  • 24
  • 47
  • Thanks for the response! How would I use pagination? I thought limitToLast only used the last 25 entries? I am new with firebase though, so I am not too sure. Thanks again! – SF Dev Nov 23 '16 at 17:10
  • I’d recommend you looking at this post for pagination (http://stackoverflow.com/questions/37144030/how-do-you-properly-order-data-from-firebase-chronologically) as it helped me, as well. – waseefakhtar Nov 24 '16 at 16:04