如何创建包含纬度/经度(使用GIST)的PostgreSQL索引,还包括常规字段

Dan*_*ola 2 postgresql indexing earthdistance

我有一个位置表,我的应用程序的用户需要能够搜索.位于"我x英里内的位置"

我正在使用这样的查询:

select * from job_locations 
   where earth_box(ll_to_earth(51.5, -0.085), 5000) @> ll_to_earth(latitude, longitude)  
   and earth_distance(ll_to_earth(51.5, -0.085), ll_to_earth(latitude, longitude)) < 5000;
Run Code Online (Sandbox Code Playgroud)

和这样的索引:

CREATE INDEX job_locations_lat_lng on job_locations USING gist(ll_to_earth(latitude, longitude));
Run Code Online (Sandbox Code Playgroud)

但是,这是一个多租户系统,其中所有表都有一个"tenant_id"字段,我们也总是按此过滤.理想情况下,我可以在索引中同时使用tenant_id和ll_to_earth(lat,lng),这可能会使搜索速度更快.

这可能吗?如何创建该索引?

谢谢!
丹尼尔

bma*_*bma 5

您可能需要btree_gis t扩展来创建索引以包含tenant_id字段,该字段似乎至少存在于Postgres 8,.4之后.

CREATE EXTENSION btree_gist;
CREATE INDEX job_locations_lat_lng ON job_locations USING gist(tenant_id, ll_to_earth(latitude, longitude));
Run Code Online (Sandbox Code Playgroud)