Skip to content

Instantly share code, notes, and snippets.

@karmi
Created June 28, 2011 14:13
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save karmi/1051213 to your computer and use it in GitHub Desktop.
Save karmi/1051213 to your computer and use it in GitHub Desktop.
Geo Distance Filter Support in Tire/ElasticSearch
require 'tire'
require 'active_support/core_ext/numeric'
require 'active_support/core_ext/time/zones'
# Tire.configure { logger STDERR, level: 'debug' }
class Time; DATE_FORMATS.update lucene: "%Y-%m-%dT%H:%M"; end
Tire.index 'venues' do
delete
# 1) Create the index with proper mapping for the `location` property
create mappings: {
venue: {
properties: {
location: { type: 'geo_point' },
updated_at: { type: 'date', format: 'date_hour_minute' }
}
}
}
# 2) Store some example documents of the `venue` type
store type: 'venue', name: 'One', location: [40.1, -70.1], updated_at: 3.hours.ago.utc.to_s(:lucene)
store type: 'venue', name: 'Two', location: [40.2, -70.2], updated_at: 2.hours.ago.utc.to_s(:lucene)
store type: 'venue', name: 'Three', location: [50, 15], updated_at: 1.hour .ago.utc.to_s(:lucene)
refresh
end
s = Tire.search 'venues' do
# 3) Search based on geo distance
filter 'geo_distance', distance: '100km', location: [40, -70]
# 4) Sort by distance to origin
# sort { by :_geo_distance, location: [40, -70] }
# 5) Sort by `updated_at` property
sort { by :updated_at, 'desc' }
end
puts s.to_curl, '-'*80
s.results.each do |d|
puts "* #{d.name} | location: #{d.location}, updated_at: #{d.updated_at}"
end
@karmi
Copy link
Author

karmi commented Aug 1, 2012

@klebervirgilio
Copy link

@karmi, Any chance to have access to the calculated "_geo_distance" value?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment