Rails Elasticsearch按地理距离排序

时间:2015-08-06 09:10:58

标签: ruby-on-rails elasticsearch

有以下型号:

# Place of the system
class Place < ActiveRecord::Base
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks

  belongs_to :user

  validates :title, :description, :address, :discount, :user, :latitude, :longitude, presence: true

  has_many :accounts, dependent: :destroy
  has_many :orders, dependent: :destroy

  settings index: { number_of_shards: 1, number_of_replicas: 0 } do
    mapping do
      indexes :location, type: 'geo_point'
    end
  end

  def location
    [latitude, longitude]
  end

  def self.search()
    __elasticsearch__.search(
      {
        query: {
          match_all: {}
        },
        sort: [{
          geo_distance: {
            location: {
              latitude: 0,
              longitude: 0 
            }
          }
        }]
      }
    )
  end
end

Place.__elasticsearch__.client.indices.delete index: Place.index_name rescue nil

# Create the new index with the new mapping
Place.__elasticsearch__.client.indices.create \
  index: Place.index_name,
  body: { settings: Place.settings.to_hash, mappings: Place.mappings.to_hash }

# Index all article records from the DB to Elasticsearch
Place.import

克林特代码:

Place.search().records.to_a

错误:

Elasticsearch::Transport::Transport::Errors::BadRequest: [400] {"error":"SearchPhaseExecutionException[Failed to execute phase [query_fetch], all shards failed; shardFailures {[SO439Vg2TIWNUREaDVzCOg][places][0]: SearchParseException[[places][0]: query[ConstantScore(*:*)],from[-1],size[-1]: Parse Failure [Failed to parse source [{\"query\":{\"match_all\":{}},\"sort\":[{\"geo_distance\":{\"location\":{\"latitude\":0,\"longitude\":0}}}]}]]]; nested: ElasticsearchIllegalArgumentException[sort option [location] not supported]; }]","status":400}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试

sort: [{'_geo_distance' => {
            location: {
              latitude: 0,
              longitude: 0 
            }
          }
        }]

如果这不成功,那么

sort: [{'_geo_distance' => {
            location: {
              lat: 0,
              lon: 0 
            }
          }
        }]