9

I have a mysql select statement for a search on my website which is having performance problems when the site gets really busy. The query below searches for adverts from a table with over 100k records, within 25 miles of the given lat and lon and sorts by distance. The number of miles can differ as it is selected by the user.

The problem is that I think it is slow because it does the calculations for all records in the table rather than ones that are within 25 miles of the lat and lon. Is it possible to amend this query so that where clause selects only adverts within 25 miles? Ive read about bounding box's and spatial indexes but im not sure how to apply them to this query, do I need to add a where clause that selects records 25 miles radius of the lat and lon, how do I do this?

SELECT 
    adverts.*, 
    round(sqrt((((adverts.latitude - '53.410778') * (adverts.latitude - '53.410778')) * 69.1 * 69.1) + ((adverts.longitude - '-2.97784') * (adverts.longitude - '-2.97784') * 53 * 53)), 1) as distance
FROM 
    adverts
WHERE 
    (adverts.type_id = '3')
HAVING 
    DISTANCE < 25
ORDER BY 
    distance ASC 
LIMIT 120,10

Edit: Updated to include table schema, please note that table is more complicated and so is the query but I have removed the things which aren't necessary for this problem.

CREATE TABLE `adverts` (
`advert_id` int(10) NOT NULL AUTO_INCREMENT,
`type_id` tinyint(1) NOT NULL,
`headline` varchar(50) NOT NULL,
`description` text NOT NULL,
`price` int(4) NOT NULL,
`postcode` varchar(7) NOT NULL,
`latitude` float NOT NULL,
`longitude` float NOT NULL,
PRIMARY KEY (`advert_id`),
KEY `latlon` (`latitude`,`longitude`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

when i do an explain on the mysql statement the number of rows is set to 67900 which is a lot more than is in a 25 mile radius, also the extra is set to "Using where; Using filesort".

The query takes 0.3 seconds which is really slow, especially when the websites gets lots of requests per second.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user1052096
  • 853
  • 4
  • 13
  • 23
  • I've already noticed a couple problems with this query and I have a few ideas on how to make it a lot quicker, Can you give us a preview of the table schema? (your primary key etc) – classicjonesynz Sep 19 '12 at 12:28

2 Answers2

8

The fastest way to do this is to use the geospatial extensions for MySQL, which should be easy enough as you are already using a MyISAM table. The documentation for these extensions can be found here: http://dev.mysql.com/doc/refman/5.6/en/spatial-extensions.html

Add a new column with a POINT datatype:

ALTER TABLE `adverts` 
ADD COLUMN `geopoint` POINT NOT NULL AFTER `longitude`
ADD SPATIAL KEY `geopoint` (`geopoint`)

You can then populate this column from your existing latitude and longitude fields:

UPDATE `adverts` 
SET `geopoint` = GeomFromText(CONCAT('POINT(',`latitude`,' ',`longitude`,')'));

The next step is to create a bounding box based on the input latitude and longitude that will be used in your WHERE clause as a CONTAINS constraint. You will need to determine a set of X,Y POINT coordinates that work for your requirements based on the desired search area and given starting point.

Your final query will search for all POINT data that is within your search POLYGON, and you can then use a distance calculation to further refine and sort your data:

SELECT a.*, 
    ROUND( SQRT( ( ( (adverts.latitude - '53.410778') * (adverts.latitude - '53.410778') ) * 69.1 * 69.1 ) + ( (adverts.longitude - '-2.97784') * (adverts.longitude - '-2.97784') * 53 * 53 ) ), 1 ) AS distance
FROM adverts a
WHERE a.type_id = 3
AND CONTAINS(a.geopoint, GeomFromText('Polygon((0 0,0 3,3 3,3 0,0 0))'))
HAVING distance < 25
ORDER BY distance DESC
LIMIT 0, 30

Note that the GeomFromText('Polygon((0 0,0 3,3 3,3 0,0 0))') in the above will not work, you will need to replace the coordinates with valid points around your search start. If you expect the lat/long to change, you should consider using a trigger to keep the POINT data and associated SPATIAL KEY up to date. With large datasets you should see vastly improved performance over calculating a distance for every record and filtering using a HAVING clause. I personally defined functions for use in determining the distance and creating the bounding POLYGON.

doublesharp
  • 26,888
  • 6
  • 52
  • 73
  • How do I define the `Polygon()` using the input Lat/Lon? Eg. a square that is 25miles to each edge from the input lat/lon, or an approximation of a circle that has a radius of 25miles and is centered at the input lat/lon, etc. – T. Brian Jones Nov 04 '16 at 00:06
  • 1
    It depends on how accurate you want to be. Each degree of longitude is ~54.6 miles, and each degree of latitude is ~69 miles at the equator and approaches 0 at the poles. Just google "calculate bounding box using latitude and longitude" for articles on the topic. – doublesharp Nov 04 '16 at 02:25
6

There a few ways to speed up your query, personally I'd take advantage of the POW function.

Returns the value of X raised to the power of Y.

Manual multiplication will slow your query down with large tables, although achieving the same result.

SELECT a .* , 
    round( sqrt( 
        (POW( a.latitude -'53.410778', 2)* 68.1 * 68.1) + 
        (POW(a.latitude -'-2.97784', 2) * 53.1 * 53.1) 
     )) AS distance
 FROM adverts a
     WHERE a.type_id = 3
     HAVING distance < 25
     LIMIT 0 , 30

The above query runs in 0.0008 sec on table schema with 10,000 records (Your query tested on the same table schema took 0.0129 sec), so it was a considerable increase in performance.

Other Optimization Tips

  • An sql query becomes faster if you use the actual columns names in SELECT statement instead of *.
  • Fully reference the table name mydatabase.mytable.
  • If you have to ORDER BY use the primary key (Its an indexed field, or create an index on the field you intend on ORDERING).
  • Use mysql framework functions for math calculations it will speed up the process.
  • And finally try and make your queries as simple as possible with these steps (the simpler the faster).

Sources

classicjonesynz
  • 4,012
  • 5
  • 38
  • 78
  • Thanks, I didnt think I could reference a.DISTANCE in the where clause as distance is calculated in the select, it isnt actually a field in the table. – user1052096 Sep 19 '12 at 12:59
  • After doing more reading and I've found the `WHERE Clause` doesn't actually have access to `user-defined` variables. I've edited my answer where appropriate. Regards – classicjonesynz Sep 19 '12 at 22:16
  • updated the answer with some results from `testing` on a table with `10,000` records. – classicjonesynz Sep 19 '12 at 22:26
  • Hi, Thanks for the update, yourquery will be faster because it doesnt have the order by distance clause which slows down the query considerably but it is needed. This still doesnt answer my original question though, if the table holds 100,000 records, it will do the distance calculation on the whole 100,000 records regardless of the having statement. I wanted to update the query so that it has a where clause that only includes records within 25 miles of the latitude and longitude. – user1052096 Sep 20 '12 at 08:50
  • Can't you sort (`ORDER BY ASC`) on the data after it has arrived? out of mysql? in your apps language? (each language has a way of sorting for you [`python`](http://docs.python.org/howto/sorting.html), [`php`](http://php.net/manual/en/function.sort.php), [`java`](http://viralpatel.net/blogs/java-tip-how-to-sort-array-in-java-java-util-arrays/), [`c++`](http://mathbits.com/MathBits/CompSci/Arrays/Sorting.htm) to name a few) – classicjonesynz Sep 21 '12 at 11:14
  • you need to calculate the upperleft and the bottomright coordinates of the MBR rectangle. With that information you can filter out most records really fast if you put an index on the lat long columns. At last you perform the Haversine algoritm to get a more accurate result. This is the only way to optimize your query. Except if you can use the spatial functions as of MysQl 5.6, but I don't know about there performance. – Richard May 07 '13 at 21:27
  • Hey @Killrawr, I'm very new this functionality and want to get some help, my question is, I have a table of news which contains latitude and longitude, I have latitude and longitude of a location, now what I want is to fetch all the news within 10 miles of the latitude and longitude I have. Please help me with this. Thanks – Rohit Khatri Aug 19 '16 at 16:15
  • @RohitKhatri I'm on mobile internet at the moment but I'll see what I can do on Monday – classicjonesynz Aug 19 '16 at 23:36
  • @RohitKhatri try http://stackoverflow.com/questions/8994718/mysql-longitude-and-latitude-query-for-other-rows-within-x-mile-radius – classicjonesynz Aug 19 '16 at 23:52
  • @Killrawr Thank you so much, that is what I was looking for. – Rohit Khatri Aug 20 '16 at 04:21
  • @Killrawr Is there any other solution for fast results, because the reference you gave is taking like 5 minutes to provide the result, I've 0.6 million rows in the table. and It also gives me some error after completion `Notice in ./libraries/sql-parser/src/Utils/Query.php#570 Undefined index: ORDER BY` – Rohit Khatri Aug 20 '16 at 12:30
  • @RohitKhatri could try reducing the amount of data pull only primary key and distance, then fill in the gaps for more data with another query. – classicjonesynz Aug 20 '16 at 12:33
  • @RohitKhatri instead of searching using the equations provided maybe, you might need to index the value from a base equation then use that information against an input value (this would reduce the amount of work necessary by the server if the work has already been done in advance) best of luck buddy – classicjonesynz Aug 20 '16 at 12:55
  • @Killrawr Are you saying about creating index for latitude and longitude columns in the table? If not, make me understand please. – Rohit Khatri Aug 20 '16 at 13:00
  • @RohitKhatri I'm saying that the result from putting Lat and long through cos,sin,tan remains constant whereas the user input changes, so in order to see performance save the result that will be multiplied against the user input before hand instead of running the same calculation over and over which delays the output of your data, thus reducing the amount of work needed. E.g. If I know 4x5 is always going to be 20, I can cache that value instead of working it out 500,000 times. – classicjonesynz Aug 20 '16 at 13:15
  • @Killrawr Ohh you are suggesting that I should cache the result. Well that's a good idea, but I don't know how to cache the result, do I have to store it in the database? – Rohit Khatri Aug 20 '16 at 13:32
  • @RohitKhatri yes add whatever additional columns to the table and track data that remains constant, this requires more prep but in the long run you will see improvements in your extraction – classicjonesynz Aug 20 '16 at 13:34
  • Well, I don't know how to do that, will read something on it. – Rohit Khatri Aug 20 '16 at 15:49