首页
/ ActiveRecord + PostgreSQL Earthdistance 使用指南

ActiveRecord + PostgreSQL Earthdistance 使用指南

2024-12-27 13:18:57作者:彭桢灵Jeremy

本文档旨在帮助用户安装、使用ActiveRecord与PostgreSQL Earthdistance扩展,并提供相关的API使用说明。

1. 安装指南

系统要求

  • PostgreSQL 9.1+ 版本,并安装 contrib 扩展
  • Rails 3.1+ 版本

在 Ubuntu 系统上,安装 contrib 扩展非常简单:

sudo apt-get install postgresql-contrib-9.1

在 Mac 系统上,您有以下几个选项:

  • 使用 EnterpriseDB 提供的二进制包
  • 使用 Homebrew 安装 Postgres,它包括了 contrib 包:brew install postgres
  • 使用 Postgres.app

安装步骤

  1. 确保 Earthdistance 是 PostgreSQL 的 contrib 模块,请先查阅相关文档。
  2. 将以下代码添加到 Gemfile 中:
gem 'activerecord-postgres-earthdistance'

然后运行 bundler:

bundle install
  1. 创建一个迁移文件来为 PostgreSQL 数据库添加 earthdistance 支持:
rails g earth_distance:setup

运行迁移:

rake db:migrate
  1. 为模型添加地理索引以加快查询速度。例如,为 Place 模型添加索引:
rails g migration add_index_to_places

编辑生成的迁移文件:

class AddIndexToPlaces < ActiveRecord::Migration
  def up
    add_earthdistance_index :places
  end

  def down
    remove_earthdistance_index :places
  end
end

这将创建类似的 SQL 索引:

CREATE INDEX places_earthdistance_ix ON places USING GIST (ll_to_earth(lat, lng));

2. 项目的使用说明

在 Gemfile 中添加以下代码:

gem 'activerecord-postgres-earthdistance'

在每个具有经纬度字段的模型中添加 acts_as_geolocated 方法。例如,对于具有 latlng 字段的 Place 模型:

class Place < ActiveRecord::Base
  acts_as_geolocated
end

您也可以为不同的字段名指定 acts_as_geolocated

class Place < ActiveRecord::Base
  acts_as_geolocated lat: 'latitude_column_name', lng: 'longitude_column_name'
end

对于关联模型的地理定位:

class Job < ActiveRecord::Base
  belongs_to :job
  acts_as_geolocated through: :job
end

查询数据库

查询给定半径内的所有地点:

Place.within_radius(100, -22.951916, -43.210487).all

根据距离排序:

Place.within_radius(100, -22.951916, -43.210487).order_by_distance(-22.951916, -43.210487)

关联模型的查询:

Job.within_radius(100, -22.951916, -43.210487)

如果不需要精确距离,可以使用更快的 bounding box 查询:

Place.within_box(1_000_000, -22.951916, -43.210487)

获取距离:

point = [-22.951916, -43.210487]
closest = Place.within_radius(100, *point).order_by_distance(*point).selecting_distance_from(*point).first
closest.distance

3. 项目API使用文档

项目的 API 使用主要是通过 acts_as_geolocated 方法以及相关查询方法来实现。以下是部分方法的简要说明:

  • acts_as_geolocated: 在模型中启用地理定位功能。
  • within_radius: 查询给定半径内的所有记录。
  • order_by_distance: 根据与指定点的距离排序记录。
  • within_box: 使用 bounding box 方法快速查询给定范围内的记录。
  • selecting_distance_from: 在查询结果中包含与指定点的距离。

4. 项目安装方式

请参照“安装指南”中的步骤进行安装。

登录后查看全文
热门项目推荐