Geo Code

Hyperpublic Local Data Engineering Blog
Dec 21

An Introduction to the Hyperpublic API, useful Python tools, and .... NYC Pizza

The following post was written by our newest team member @deland, and it is something between an introduction to the Hyperpublic API and a documentation of a first experience with it. The actual use case described below is just a toy application - but it provided an opportunity for some cool visualizations. We hope you enjoy it and come up with some cool uses of your own!

If you haven't already, the first thing you're going to need to do to get started with the API and follow along (or experiment on your own) is to register for a Hyperpublic API key. It's free! It's fun! There are API wrappers for many programming languages so you can choose your favorite and get started right away. I'm going to be describing my method using Python, but the syntax in all the languages is pretty straightforward.

We're going to focus on pizzerias in New York City because everyone loves pizza (and because we had to choose something). The Hyperpublic API is a window into the world indexed by (exact) location. We can query the API by sending it addresses, zip codes, phone numbers, or latitudes and longitudes as well as categorical information (more on this in a moment). The query we send the API is then resolved to a specific latitude and longitude, and nearby places satisfying the query are returned. This means if we send the API a generic location like "New York, NY", a specific latitude and longitude is set, and then the search is executed. What this really means is you may not get what you wanted if you use such a generic location! The parameters available to query the API are described here, as is the structure of the documents that will be returned to you.

The categorical information in included in the query quite easily. We ask for places with a specific category (restaurant, office, etc) or we can ask for the database to be searched for other text (via the parameter 'q', for query). All locations with a place-name or tag matching your text will be returned. So we will query the API using the location parameter and also q = 'pizza'. For reasons that will become clear soon, I took the result of the queries and stored them in a local Mongo database . To be able to get all pizzarias in new york city, I looped over all the zipcodes in new york. The API only returns 50 locations at a time, but we can ask for more. Here is the relevant code:

 

from hyperpublic import *
...
for zip in zipcodes:
   inserted = 0
   notinserted = 0
   for p in range(1,rounds + 1):
      try:
         items = hp.places.find(location=str(zip),q="pizza", page = p, page_size = 50)
      except:
         break
      for item in items:
         try:
            dbh.nypizza.insert(item, safe = True)
            inserted += 1;
         except DuplicateKeyError:
            notinserted += 1
    print "%d items inserted and %d duplicates found for zipcode %d" % (inserted, notinserted, zip)

Here, my local mongodb connection is called dbh and the collection is called nypizza. Because some zip codes don't cover that much area - many of these queries will return the same pizzerias as other queries. This may not be a problem depending on your application, but you also might want to be aware of it (I just prevented mongo from duplicating records by inserting a key on the id field). Now we have the location of all (I get 2439) pizza places in the city - how easy was that?!

Probably we want to visualize all the locations at once. There are many options for doing this - and many existing python libraries to make our lives easier. For visualization only, my favorite tool (so far) was created by Seth Golub. It creates a heatmap based on density of points, and can overlay the 'heat' on top of maps coming from OpenStreetMap . This image is available under CC-BY-SA.

Pizza

Depending on your needs, you can also overlay this information onto Google Earth maps or Gmaps. The nicest tool I found for this is hosted here. The interface is incredibly easy. Here is the output (it spits out kml data which google earth can read, and can also be accessed by google maps):

Pizza_map
 Let's visualize the network of pizzerias in the city. I inserted a geo index on the mongo database. Then for every pizza place X, I can query the database for all other pizzerias within .1 miles (roughly) of X. Every time I find a relationship like this, I create an edge in a graph using the awesome network/graph software package at NetworkX. Here is the result:

Pizza_graph3

You might start wondering, "if I wanted to go on a 'pizza-slice' tour of new york city, and I wanted the longest sequence of pizzerias separated by .1 miles without visiting any place twice - what would I do?". Coincidentally, I wondered the exact same thing, and wrote a short function to search the graph for the longest such path. (For those who care, finding the longest path in a graph with cycles is known to be NP-hard. So don't try this on your big graphs.) Here is the result, you can visit 32 pizzerias (labeled, in order,it A-Z, then 0-5). Best of luck.

Pizza_tour

Nov 2

APIs For Beginners @Hyperpublic

On Thursday, November 3rd, Hyperpublic's head of engineering, Doug Petkanics, will be teaching a Skillshare class called "APIs For Beginners." The class will start with the basics, and will cover the following:

  • What is an API?
  • What type of data and services do companies make available via APIs?
  • Why would I use APIs?
  • How do I use APIs?
There is no prior programming experience required, but as APIs are quite literally "programming interfaces", you will have to do some light programming in order to make use of the data you get through the APIs. 

We'll talk about APIs from companies like Flickr, Paypal, Google, and Twitter. You'll learn how to get data from them and what you can do with their services. If you're interested in getting started with building web applications, then this class will provide a good introduction to the types of data and services you can leverage to speed up your development and enhance your applications.

Limited tickets are still available so sign up today. All proceeds from the ticket sales will be donated to HackNY.

Sep 28

Introducing the Hyperpublic API

The last few months have been busy at Hyperpublic and we’d love to tell you about two great local data APIs: Places+ and Geo Deals and Events.

Places+ returns nearby businesses and other points of interest (POI). Our places data set has freshest and most accurate information from the web. You can query the API from many popular languages and use it in your web and mobile applications.

Geo Deals and Events is a collection of real time local offers including daily deals, meet ups, exhibitions and other types of events that can be integrated into any app or web service. When your users interact with these offers, you get paid through our local offers monetization plan.

For this post, we'll focus on calling the API through simple URLs that you can try in your browser. We’ll walk through what the requests and results look like and how they're constructed.

The Places+ API returns points of interest around a specific location. Here are places around Hyperpublic HQ:

Click and you'll get a block of raw JSON. 

That's an array of JSON objects: each one represents a place in the Places+ database. Each place includes useful information like its name, lists of tags and properties, and its locations with street address and latitude/longitude.

In most cases, API calls are simply GET requests to (carefully constructed) URLs. Let’s review each piece of the example above:

  • https://api.hyperpublic.com/api/v1 — This is the base URL for Hyperpublic API requests. Hyperpublic requires SSL for all requests.
  • /places — Include this path after the base URL to access the Places+ endpoint. Other endpoints use different paths.
  • ?...&...&... — These are query parameters. Following the ? is an &-separated list of key=value pairs. You use these to define your search and pass your authorization credentials:
    • address=416%20W%2013th%20St%2C%20NY%2C%20NY%2C%2010014 — The address parameter takes a URL-encoded address. For this example, we URL encoded "416 W 13th St., New York, NY, 10014".
    • client_id=..., client_secret=... — These are the Client ID and Client Secret values you're given when you register an application. They must be included in every API call. (The values used in this post are just for documentation and examples. Don't use them in your own applications!)

By default, all location queries return at most 10 results inside a 2 km radius. You can override the defaults by passing the relevant query parameters. To get more results, include limit=50, or to search within a 0.5 km radius, include radius=0.5. How about the closest Japanese restaurant to Madison Square Garden? Combine category=japanese with the lat, lon, and limit parameters, and you're there:

You can get a specific place by making requests to /places/ID, where ID is the value of the id field in that place’s JSON representation. Here's how to get that same sushi restaurant without searching:

Calling the Geo Deals and Events endpoint is as easy as substituting /offers for /places in the request URL. The basic search and show functionalities are the same as with Places+, but some of the query parameters are different. Let's find offers near Prospect Park, Brooklyn, that cost less than $50:

And we can request a specific offer the same way we requested a specific place:

This is a basic introduction to the Hyperpublic API; check out the API documentation for a full reference. The documentation pages will be updated with new features as we roll them out, so check back often! Our Geo Code blog will have more posts to show how to use language-specific libraries to easily integrate Hyperpublic into your applications.

Got questions? Post to our API Developers Google Group and we'll be glad to help you out. Happy hacking!

May 31

Migrating From PostgreSQL to MongoDB at Hyperpublic

The engineering team at Hyperpublic has been hard at work over the last few weeks re-architecting our platform in order to migrate from a relational database (PostgreSQL) to a NoSQL datastore (MongoDB). We completed the migration about two weeks ago, and nothing major has broken down so far, so it's about time to do a recap so that the community can benefit from what we learned along the way. This post starts off anecdotal and moves to technical, and hopefully after reading it you'll have a good background on the reasons why you may want/need to migrate and how to go about performing the migration.

Where we came from
The Hyperpublic platform was originally built using Ruby on Rails on the Heroku platform in order to speed development time and iterate quickly. Until we discovered our true utility as an open rich location data platform, there was no sense in over engineering a custom system for performance and reliability. As a result, our choice of database was made for us by Heroku, which only supports PostgreSQL out of the box. This was fine, as most local objects were being added to our system by our users, and we were only adding objects within a couple major US cities in order to prove the concept and utility of our platform.

For those of you not familiar with Hyperpublic, what we do is provide a rich data layer on top of local objects. For every real world person, place, or thing we want to be able to provide developers with the object's physical location, tags that describe it, photos, descriptions, and various properties that will be useful to anyone building an application that could use local data. Since the data was modeled relationally, you can probably make some accurate guesses about the database tables that we defined:

  • People
  • Places
  • Things
and each of the above have many different...
  • Locations
  • Images
  • Tags
  • Properties

...among others.

So what was the problem?
When Hyperpublic began to grow we began building up the data programmatically. The number of local objects that we had in our database increased and we found our niche as a data provider, we began to run into our first two problems of scale.

As you can imagine, in order to return a local object to a user making an API call or viewing our application at Hyperpublic.com, we would have to join on all of the above tables. This was slow. Also, it felt illogical that we would constantly have to join across a normalized data structure to receive images, tags, locations, and properties for a given place, when those images, tags, locations, and properties only belonged to one specific place every time. 

The second problem that we faced was support for geo-spatial queries. Without using a geo-extension for PostgreSQL called PostGIS, in order to do proximity, bounding-box/radius, and nearest-neighbor queries you have to do math on the stored lat/lon for every point in your system. This means a table scan, and when you get beyond one or two cities worth of local object data in Hyperpublic, this gets very slow. We began researching and educating ourselves on PostGIS. It is undoubtedly a reasonable option to solve the types of problems we were facing, but the implementation felt less than clean. It felt ugly to program against, and it felt tacked onto Postgres instead of embedded within it from the beginning.

Enter MongoDB
While evaluating solutions for the above problems we were looking for a database that could store the arbitrary properties and undefined quantities of metadata along with each object. This is the prototypical usecase for a NoSQL datastore. Additionally, we were looking for geo-spatial index and query support: one of the oft-focused-upon features of MongoDB. We knew that the 10gen team was here in NYC as we've participated in many events and conferences in which they've been present, and they're very supportive of startups building on their technology. The choice to migrate to MongoDB was obvious being that they support all of the near term features that we require from a datastore. Then it was just a matter of how we would do the migration...

How we migrated
(Note - this section is somewhat Rails/ActiveRecord/Mongoid heavy, but you can replace these terms with your frameworks and ORM/ODM of your choice).

Step 0 - Have a unit test suite with good coverage on your models and make sure all your tests pass.

Step 1 - Write scripts to copy your data into MongoDB. Do not delete/change anything in the current schema.

In a non-optimized Rails application, the closest that you get to your database is by writing your model classes using the ActiveRecord object-relational mapper. When switching to MongoDB we chose to use the Mongoid object-document mapper as a non-quite-dropin replacement for ActiveRecord.Our migration script first namespaced the Mongoid objects, defined the collections they would be stored in, and defined the fields that would be mapped in each collection. It looked something like this...

The goal of the data migration scripts is to instantiate your ActiveRecord objects and then insert them into Mongo using Mongoid objects. (You can bypass Mongoid and go straight to MongoDB using the ruby driver, however Mongoid gives you some conveniences like relationships and timestamps). We opted to always instantiate the objects, however we would do so using a queue and background jobs so that we wouldn't exceed the memory on the server by instantiating every single object in one process. Our script would basically just map the data from AR to Mongoid like so...

Notice that we are copying the old_id from AR to Mongoid. This has proven useful many times over when needing to do lookups after the fact, and I recommend you keep it around for awhile until you are certain that you'll never need it again. Regarding ID's, keep in mind that your object ID's will change. You'll need to update any external resources that refer to the old object ID's. For example, our Amazon S3 was configured to store photos in buckets named after the object's ID.

After your script is written, you should be able to safely run it on a copy of your production dataset as a test, since it won't modify or delete any production data.

Step 2 - Update your application
At this point, you'll want to create another branch to update your application. The reason is because the migration needs to reference the ActiveRecord models in the current application, so you can't delete or modify them until all the data is copied over. On a separate branch, you can update your models to use Mongoid instead of ActiveRecord. The meat of this process can be copied over from the models you created during your data migration. When you do eventually get your application working again with the updated models, update and run your unit tests to make sure that they all pass.

Step 3 - Configure your production MongoDB environment
We won't go into details here, but we recommend at least a 3 node replica set configuration. MongoDB has a good writeup on how to set this up here.

Step 4 - Deploy to production
Backup your database and take your application down for maintenance so that no writes come in after the data migration. Deploy the branch with your data migration and run it. Assuming all goes well, deploy the second branch with your updated application. Restart your application and you'll be up and running on MongoDB.

The results
I don't have hard numbers so this is going to be more anecdotal than scientific, but after migrating to MongoDB the Hyperpublic platform was immediately faster and more scalable than it was previously. We've seen over 5x speed increases in the user facing application and 20x speed increases within our API. 

Geospatial queries now use the indexes computed ahead of time and return instantly instead of doing table scans and distance computing math on each query. 

Loading all of the metadata associated to a local object is now completed without any joins, and the number of queries per page was reduced dramatically.  

We went from 2 cities worth of data pushed into the production system as a proof of concept, to 10+ cities worth of data pushed in and usable by third party developers off of our live platform with no performance bottlenecks in site in the near term.

Gotchyas and lessons learned
10gen is iterating very quickly on MongoDB, and as a result programming against it is sometimes a moving target. Here are some of the lessons learned along the way during the migration:

  • MongoDB has great support for geo-spatial indexes, but if you want multiple locations indexed per document, you'll have to use MongoDB 1.9. Our "People" can have multiple locations - where they live, where they work, etc - so this was a requirement for us. 1.9 is supposedly unstable and not recommended for production use, but we have been quite happy with it.
  • The ODM's likely won't be fully featured, up-to-date, or drop-in replacements for the ORM you may have been using with PostgreSQL. If you're a beginner, I recommend getting very familiar with the MongoDB driver for the language of your choice, as you'll frequently have to drop down to it directly.
  • Do not try to model things relationally in MongoDB. If your problem is suited to relational modeling, then stick with a relational DB. 
  • Keep old postgres ID's around. You frequently have to refer to them when doing in memory "joins" with your old relational data or when referring to legacy data stored in external services.
  • The MongoDB community and 10gen are very helpful. Talk to people at local meetups and conferences, and they're usually happy to help you with any issues you have in your migration to MongoDB.

I hope this post was useful. If you're migrating to MongoDB and have any questions or could use some help, drop me a line anytime @petkanics on twitter.

About Geo Code

Geo Code is the engineering blog of Hyperpublic, an open location platform.
Tumblr

Search Blog

Get Updates

Tags

Archive

2011 (27)