我有一个数据库,其中包含 50 万个位置,有时甚至超过 100 万个位置。
我网站上的用户输入他们的邮政编码,我需要向他们显示按距离排序的位置。当我的数据库中只有 10 万个位置时,这实际上非常快,但现在需要 3 秒以上,即使在非常大的 VPS 实例上也是如此。
这是我使用 lat/lng 并按距离搜索的查询:
select *,
( 3959 * acos( cos( radians(41.8817767) ) *
cos( radians( lat ) )
* cos( radians( lng ) - radians(-87.6371461)
) + sin( radians(41.8817767) ) *
sin( radians( lat ) ) )
) AS distance from `locations` where `locations`.`deleted_at` is null having `distance` < '500' order by `distance` asc limit 500
我可以做些什么来加快速度?我可以继续升级我的服务器,但很快就会变得昂贵。
最佳答案
我建议使用 Elasticsearch ,因为它内置了对 GIS/距离计算的支持。
将您的对象添加到 Elastic Search,然后将距离和对象标识符列表提供给您的 MySQL 表。从查询(如下)中返回列表后,只需获取从搜索中选择的那些对象。
GET /attractions/restaurant/_search {
"query": {
"filtered": {
"filter": {
"geo_bounding_box": {
"type": "indexed",
"location": {
"top_left": {
"lat": 40,8,
"lon": -74.0
},
"bottom_right": {
"lat": 40.4,
"lon": -73.0
}
}
}
}
}
},
"sort": [
{
"_geo_distance": {
"location": {
"lat": 40.715,
"lon": -73.998
},
"order": "asc",
"unit": "km",
"distance_type": "plane"
}
}
]
}
(摘自 https://www.elastic.co/guide/en/elasticsearch/guide/current/sorting-by-distance.html 的片段)
关于php - 使用 50 万个项目加快邮政编码距离搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31700982/