class School < ActiveRecord::Base
include Tire::Model::Search
attr_accessor :location
attr_accessible :name, :address, :latitude, :longitude
state_machine :status, initial: :active do
state :active
state :deleted
event :set_active do
transition all => :active
end
event :set_deleted do
transition all => :deleted
end
end
after_save do
if self.active?
tire.update_index
else
self.index.remove self
end
end
def self.search(params)
longitude = params[:lng].to_f
latitude = params[:lat].to_f
params[:page] ||= 1
params[:per_page] ||= 20
tire.search(page: params[:page], per_page: params[:per_page], load: true) do
query do
boolean do
must { string params[:keyword], default_operator: "AND" } if params[:keyword].present?
end
end
if latitude != 0 && longitude != 0
sort do
by :_geo_distance, { location: [longitude, latitude], order: "asc", unit: 'km' }
end
end
end
end
def location
{ longitude: longitude.to_f, latitude: latitude.to_f }
end
self.include_root_in_json = false
def to_indexed_json
{ id: id,
name: name,
address: address,
location: location
}.to_json
end
mapping do
indexes :id, :type => 'integer', :index => 'not_analyzed'
indexes :name, :boost => 100, analyzer: "snowball"
indexes :address, :boost => 5, analyzer: "snowball"
indexes :location, :type => 'geo_point'
end
end
Fog Creek Software 如何使用 Elasticsearch 使 Kiln 的搜索速度提升了 1000 倍(非常值得借鉴): http://www.infoq.com/cn/articles/kiln-elasticsearch/
Realtime Search: Solr vs Elasticsearch(图形并茂,很有说服力): http://blog.socialcast.com/realtime-search-solr-vs-elasticsearch/