views:

129

answers:

7

This is more of a challenge question than something I urgently need, so don't spend all day on it guys.

I built a dating site (long gone) back in 2000 or so, and one of the challenges was calculating the distance between users so we could present your "matches" within an X mile radius. To just state the problem, given the following database schema (roughly):

USER TABLE UserId UserName ZipCode

ZIPCODE TABLE ZipCode Latitude Longitude

With USER and ZIPCODE being joined on USER.ZipCode = ZIPCODE.ZipCode.

What approach would you take to answer the following question: What other users live in Zip Codes that are within X miles of a given user's Zip Code.

We used the 2000 census data, which has tables for zip codes and their approximate lattitude and longitude.

We also used the Haversine Formula to calculate distances between any two points on a sphere... pretty simple math really.

The question, at least for us, being the 19 year old college students we were, really became how to efficiently calculate and/store distances from all members to all other members. One approach (the one we used) would be to import all the data and calculate the distance FROM every zip code TO every other zip code. Then you'd store and index the results. Something like:

SELECT  User.UserId
FROM    ZipCode AS MyZipCode
        INNER JOIN ZipDistance ON MyZipCode.ZipCode = ZipDistance.MyZipCode
        INNER JOIN ZipCode AS TheirZipCode ON ZipDistance.OtherZipCode = TheirZipCode.ZipCode
        INNER JOIN User AS User ON TheirZipCode.ZipCode = User.ZipCode
WHERE   ( MyZipCode.ZipCode = 75044 )
        AND ( ZipDistance.Distance < 50 )

The problem, of course, is that the ZipDistance table is going to have a LOT of rows in it. It isn't completely unworkable, but it is really big. Also it requires complete pre-work on the whole data set, which is also not unmanageable, but not necessarily desireable.

Anyway, I was wondering what approach some of you gurus might take on something like this. Also, I think this is a common issue programmers have to tackle from time to time, especially if you consider problems that are just algorithmically similar. I'm interested in a thorough solution that includes at least HINTS on all the pieces to do this really quickly end efficiently. Thanks!

+2  A: 

You could shortcut the calculation by just assuming a box instead of a circular radius. Then when searching you simply calculate the lower/upper bound of lat/lon for a given point+"radius", and as long as you have an index on the lat/lon columns you could pull back all records that fall within the box pretty easily.

babtek
A: 

Not every possible pair of zip codes are going to be used. I would build zipdistance as a 'cache' table. For each request calculate the distance for that pair and save it in the cache. When a request for a distance pair comes, first look in the cache, then compute if it's not available.

I do not know the intricacies of distance calculations, so I would also check whether computing on the fly is cheaper than looking up (also taking into consideration how often you have to compute).

John Smith
The bit about not calculating all distances is a very good point. I suspect it'd eventually get pretty big still, with a limit of say, 100 miles. That is basically a circle between Dallas and Houston, and people on dating sites DEFINATELY drive that far to meet one another. However, I think I'll give it a whirl to see if it makes an improvement or not.
Eric
Also, a possibility is to use a SQL function to calculate distance between zip codes, and use the output from that function as a computed 'Distance' column. Then mark the column as persisted. That essentially generate the distance on the fly (which you have to do anyway) for non-cached zip pairs, and immediately return distances that are already calculated without an additional 'peek' anywhere first to decide if the work has to be done.
Eric
A: 

I would use latitude and longitude. For example, if you have a latitude of 45 and a longitude of 45 and were asked to find matches within 50 miles, then you could do it by moving 50/69 ths up in latitude and 50/69 ths down in latitude (1 deg latitude ~ 69 miles). Select zip codes with latitudes in this range. Longitudes are a little different, because they get smaller as you move closer to the poles. But at 45 deg, 1 longitude ~ 49 miles, so you could move 50/49ths left in latitude and 50/49ths right in latitude, and select all zip codes from the latitude set with this longitude. This gives you all zip codes within a square with lengths of a hundred miles. If you wanted to be really precise, you could then use the Haversine formula witch you mentioned to weed out zips in the corners of the box, to give you a sphere.

Wow, after finishing typing all that, I just saw babtek's answer, who explained it in a far simpler manner than I did, but I really don't want to delete all this.

David Watson
+1  A: 

You could divide your space into regions of roughly equal size -- for instance, approximate the earth as a buckyball or icosahedron. The regions could even overlap a bit, if that's easier (e.g. make them circular). Record which region(s) each ZIP code is in. Then you can precalculate the maximum distance possible between every region pair, which has the same O(n^2) problem as calculating all the ZIP code pairs, but for smaller n.

Now, for any given ZIP code, you can get a list of regions that are definitely within your given range, and a list of regions that cross the border. For the former, just grab all the ZIP codes. For the latter, drill down into each border region and calculate against individual ZIP codes.

It's certainly more complex mathematically, and in particular the number of regions would have to be chosen for a good balance between the size of the table vs. the time spent calculating on the fly, but it reduces the size of the precalculated table by a good margin.

Jander
This seems like a REALLY fast way of getting some indexing done, but with a much smaller (and therefore more useable) indexed data set. This **might** turn out faster than the solution I posted below. I say might because I have not thought it through. I suspect variation of this can be used to get ZipCodes that are **known** to be within range, and allow me to do a boxed select by Lat and Long, and then user the Haversinse Formula to calculate a much smaller number of distances.
Eric
Zipcodes aren't approximately equal in size though. I think there are better solutions for doing this spatial breakdown.
Paul McMillan
For example, compare the zipcode prefix 89* with 07*. Good visualization here: http://benfry.com/zipdecode/
Paul McMillan
@Paul: Hm! Actually, in my head I was treating ZIP codes as points, but this will work with shaped zipcodes too. The roughly equally sized "regions" in my answer are meant to contain several zip codes each (or parts thereof). The idea is to do a quick, rough weed-out of regions that are obviously in or obviously out of range, so you only work with the complex, numerous, (and now variable-sized!) ZIP code regions when you have to.
Jander
Yeah. With zipcodes, the maximum dataset size means there's probably a reasonable balance with your method, since the dataset is finite. Quadtrees or R-trees are the "right" way to do it though... ;)
Paul McMillan
The point though, was that even if you treat zipcodes as points (using the centroid is a perfectly fine method here), the distribution of them across a given area means that if your regional boxes are a uniform size, you won't get even performance. Dense urban areas with many zipcodes will run substantially slower than areas in the wilds of Nevada or Wyoming.
Paul McMillan
A: 

THANK YOU all for your answers. Very fast, and very bright, all of you. I have the problem running great, and pretty much everyone's answer got used. I was thinking about this in terms of the old solution instead of just "starting over." Babtek gets the nod for stating in in simplest terms.

IF ANYBODY KNOWS HOW TO DO IT WITH SPATIAL OR GEOGRAPHY TYPES, I'M ALL EARS!

OK, I'll skip the code because I'll provide references to derive the needed formulas, and there is too much to cleanly post here.

1) Consider Point A on a sphere, represented by latitude and longitude. Figure out North, South, East, and West edges of a box 2X miles across with Point A at the center.

2) Select all point within the box from the ZipCode table. This includes a simple WHERE clause with two Between statements limiting by Lat and Long.

3) Use the haversine formula to determine the spherical distance between Point A and every point B returned in step 2.

4) Discard all points B where distance A -> B > X.

5) Select users where ZipCode is in the remaining set of points B.

This is pretty fast for > 100 miles. Longest result was ~ 0.014 seconds to calculate the match, and trivial to run the select statement.

Also, as a side note, it was necessary to implement the math in a couple of functions and call them in SQL. Once I got past a certain distance the matching number of ZipCodes was too large to pass back to SQL and use as an IN statement, so I had to use a temp table and join the resulting ZipCodes to User on the ZipCode column.

I suspect that using a ZipDistance table will not provide a long-term performance gain. The number of rows just gets really big. If you calculate the distance from every zip to to every other zip code (eventually) then the resultant row count from 40,000 zip codes would be ~ 1.6B. Whoah!

Alternately, I am interested in using SQL's built in geography type to see if that will make this easier, but good old int/float types served fine for this sample.

So... Final list of online resources I used, for your easy reference:

1) Maximum Difference, Latitude and Longitude.

2) The Haversine Formula.

3) Lenghty but complete discussion of the whole process, which I found from Googling stuff in your answers...

Thanks!

Eric
you dont need to store 1.6 billion zipcodes/distances as you're only interested in zipcodes that are within a specified radius of each other <= 25 miles or whatever. This reduces the resultset from 1.6 billion to approx. 4 million. I posted an answer along these lines which might prove of interest.
f00
+2  A: 

I'd simply just create a zip_code_distances table and pre-compute the distances between all 42K zipcodes in the US which are within a 20-25 mile radius of each other.

create table zip_code_distances
(
from_zip_code mediumint not null,
to_zip_code mediumint not null,
distance decimal(6,2) default 0.0,
primary key (from_zip_code, to_zip_code),
key (to_zip_code)
)
engine=innodb;

Only including zipcodes within a 20-25 miles radius of each other reduces the number of rows you need to store in the distance table from it's maximum of 1.7 billion (42K ^ 2) - 42K to a much more manageable 4 million or so.

I downloaded a zipcode datafile from the web which contained the longitudes and latitudes of all the official US zipcodes in csv format:

"00601","Adjuntas","Adjuntas","Puerto Rico","PR","787","Atlantic", 18.166, -66.7236
"00602","Aguada","Aguada","Puerto Rico","PR","787","Atlantic", 18.383, -67.1866
...
"91210","Glendale","Los Angeles","California","CA","818","Pacific", 34.1419, -118.261
"91214","La Crescenta","Los Angeles","California","CA","818","Pacific", 34.2325, -118.246
"91221","Glendale","Los Angeles","California","CA","818","Pacific", 34.1653, -118.289
...

I wrote a quick and dirty C# program to read the file and compute the distances between every zipcode but only output zipcodes that fall within a 25 mile radius:

sw = new StreamWriter(path);

foreach (ZipCode fromZip in zips){

    foreach (ZipCode toZip in zips)
    {
        if (toZip.ZipArea == fromZip.ZipArea) continue;

        double dist = ZipCode.GetDistance(fromZip, toZip);

        if (dist > 25) continue;

        string s = string.Format("{0}|{1}|{2}", fromZip.ZipArea, toZip.ZipArea, dist);
        sw.WriteLine(s);
    }
}

The resultant output file looks as follows:

from_zip_code|to_zip_code|distance
...
00601|00606|16.7042215574185
00601|00611|9.70353520976393
00601|00612|21.0815707704904
00601|00613|21.1780461311929
00601|00614|20.101431539283
...
91210|90001|11.6815708119899
91210|90002|13.3915723402714
91210|90003|12.371251171873
91210|90004|5.26634939906721
91210|90005|6.56649623829871
...

I would then just load this distance data into my zip_code_distances table using load data infile and then use it to limit the search space of my application.

For example if you have a user whose zipcode is 91210 and they want to find people who are within a 10 mile radius of them then you can now simply do the following:

select 
 p.*
from
 people p
inner join
(
 select 
  to_zip_code 
 from 
  zip_code_distances 
 where 
  from_zip_code = 91210 and distance <= 10
) search
on p.zip_code = search.to_zip_code
where
 p.gender = 'F'....

Hope this helps

EDIT: extended radius to 100 miles which increased the number of zipcode distances to 32.5 million rows.

quick performance check for zipcode 91210 runtime 0.009 seconds.

select count(*) from zip_code_distances
count(*)
========
32589820

select 
 to_zip_code 
from 
 zip_code_distances 
where 
 from_zip_code = 91210 and distance <= 10;

0:00:00.009: Query OK
f00
This is a good solution, but lives with an assumption of a given distance. Of course the solution I liked above grows with distance at query time, and this one doesn't. However, how many rows do you wind up if you use say, 100 miles as your outer limit? I'm not sure what the answer is without running it, but I suspect that it is MUCH bigger than 4M. I'm also not sure what the practical limit of rows in SQL server is, but I suspect I'd be pushing my luck on keeping excellent performance with that many rows.
Eric
here's a 125 million row table example that queries 340K rows but limits the result to 32 rows that uses innodb and takes advantage of a clustered primary key index as my example above http://stackoverflow.com/questions/3534597/rewriting-mysql-select-to-reduce-time-and-writing-tmp-to-disk/3535735#3535735. The runtime is 0.02 seconds.
f00
with radius of 100 miles there are 95 million rows which is still pretty trival in the scheme of things. i'll edit my post with some performance testing for you to review.
f00
comment above should read 33 million not 95 was looking at the wrong data - oops.
f00
+6  A: 

Ok, for starters, you don't really need to use the Haversine formula here. For large distances where a less accurate formula produces a larger error, your users don't care if the match is plus or minus a few miles, and for closer distances, the error is very small. There are easier (to calculate) formulas listed on the Geographical Distance Wikipedia article.

Since zip codes are nothing like evenly spaced, any process that partitions them evenly is going to suffer mightily in areas where they are clustered tightly (east coast near DC being a good example). If you want a visual comparison, check out http://benfry.com/zipdecode and compare the zipcode prefix 89 with 07.

A far better way to deal with indexing this space is to use a data structure like a Quadtree or an R-tree. This structure allows you to do spatial and distance searches over data which is not evenly spaced.

Here's what an Quadtree looks like:

alt text

To search over it, you drill down through each larger cell using the index of smaller cells that are within it. Wikipedia explains it more thoroughly.

Of course, since this is a fairly common thing to do, someone else has already done the hard part for you. Since you haven't specified what database you're using, the PostgreSQL extension PostGIS will serve as an example. PostGIS includes the ability to do R-tree spatial indexes which allow you to do efficient spatial querying.

Once you've imported your data and built the spatial index, querying for distance is a query like:

SELECT zip
FROM zipcode
WHERE
geom && expand(transform(PointFromText('POINT(-116.768347 33.911404)', 4269),32661), 16093)
AND
distance(
   transform(PointFromText('POINT(-116.768347 33.911404)', 4269),32661),
   geom) < 16093

I'll let you work through the rest of the tutorial yourself.

Here are some other references to get you started.

Paul McMillan
Paul, I had no idea I would get so many and varied responses to this question. I found yours to be particularly informative. Thank you for taking the time out of your day to provide such a thorough explanation.
Eric
Thanks! Glad you liked it. Definitely did take longer than I originally intended when I started answering the question, but I guess that's how SO works! ;)
Paul McMillan