【问题标题】:Ruby Geocoder nearbys is slow附近的 Ruby Geocoder 很慢
【发布时间】:2013-10-02 17:46:53
【问题描述】:

使用 Rails 3.2、Ruby 1.9、地理编码器 gem。我的控制器中有以下查询:

# 1500+ms to load
nearby_shops = (current_shop.nearbys(10, :order => 'overall_rating DESC')
.where(:shop_type => shop_type).includes(:photos, :active_property_list => 
:hotel_image_lists).limit(5))

# SQL
Shop Load (4045.6ms)  SELECT shops.*, 3958.755864232 * 2 * ASIN(SQRT(POWER(
SIN((36.111927 - shops.lat) * PI() / 180 / 2), 2) + COS(36.111927 * PI()
 / 180) * COS(shops.lat * PI() / 180) * POWER(SIN((-115.171229 - shops.lng)
 * PI() / 180 / 2), 2))) AS distance, CAST(DEGREES(ATAN2( RADIANS(shops.lng
 - -115.171229), RADIANS(shops.lat - 36.111927))) + 360 AS decimal) % 360 AS
 bearing FROM `shops` WHERE `shops`.`shop_type` = 'food' AND (shops.lat BETWEEN
 35.96719521688915 AND 36.25665878311085 AND shops.lng BETWEEN
 -115.3503819353204 AND -114.9920760646796 AND 3958.755864232 * 2 * 
ASIN(SQRT(POWER(SIN((36.111927 - shops.lat) * PI() / 180 / 2), 2) + 
COS(36.111927 * PI() / 180) * COS(shops.lat * PI() / 180) * POWER(SIN((
-115.171229 - shops.lng) * PI() / 180 / 2), 2))) <= 10 AND shops.id != 85155)
 ORDER BY overall_rating DESC LIMIT 5
 - shops.lat) * PI() / 180 / 2), 2) + COS(48.8582411618 * PI() / 180) * 
COS(shops.lat * PI() / 180) * POWER(SIN((2.2945044899 - shops.lng) * PI() / 
180 / 2), 2))) <= 100 AND shops.id != 517) ORDER BY distance ASC LIMIT 25
 OFFSET 0

问题在于nearbyslongitudelatitude 进行计算。我已经为longitudelatitude 列添加了索引,但它并没有改善任何东西。

我该如何改进?

P/S:我删除了不影响查询速度的无关条件。

【问题讨论】:

  • shop_type 上有索引吗?
  • 我有一个非常相似的查询,它在 Postgres 9.3 下运行时间为 98.4 毫秒。你用的是什么类型的数据库?
  • @ChrisCashwell MariaDB/MySQL。
  • 出于好奇:您创建了哪些索引?
  • @ThomasKlemm latitude, longitude, shop_type.

标签: ruby-on-rails ruby rails-geocoder


【解决方案1】:

这可能不是最精确或最优雅的解决方案,但为什么不稍微捏造一下数学。你可以编写一个 select 子句来做这样的事情:

 .select(["id, name, 69.0975851*sqrt(POWER(shops.lat-?,2) + COS(?*PI()/180)*POWER(shops.lon-?,2)) AS DISTANCE", loc.lat, loc.lat, loc.lon])

如果您只是处理较小的(

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    相关资源
    最近更新 更多