简体   繁体   中英

Rails 3 Sunspot solr search within bounds

I have a question to ask regarding the new Sunspot/solr feature: restriction with near I have (via the google geocoding API) the viewport and the bounds which are latitude/longitude coordinates of the southwest and northeast corners of a bounding box. I want Sunspot/Solr to search within this bounding box but I haven't figured it out yet. So my question is: Is it possible to make Solr (or via any of the solr plugins) capable for searches within a bounding box? If yes, how?

Thank you

You can just create a lat and lng field of type trie double, and then do two range queries (one for a lat range, one for a lng range).

class Product < ActiveRecord::Base
  seachable do
     double :latitude
     double :longitude
  end
end

# search
Product.search do
  with :latitude, 36.5667..80.4553 
  with :longitude, 76.4556..67.9987
end

Sunspot supports spartial search using Geohash, see RestrictionWithNear . But you can only use the predifined distance (though :precision ).

# model
# lat: decimal
# lng: decimal
class Product < ActiveRecord::Base
  seachable do
    location :location do
      Sunspot::Util::Coordinates.new(lat, lng)
    end
  end
end

# search
Product.search do
  # near(lat, lng)
  with(:location).near(76.4556, 67.9987, :precision => 3)
end

Sparcial is added in solr starting from 3.1, I cannot find correspondng DSL in sunspot, but you can always use adjust_solr_params to add customized parameters:

Product.search do
  adjust_solr_params do |params|
    parmas[:fq] << '{!geofilt pt=74.4556,67.9987 sfield=location d=5}'
  end
end

You have to use Solr 3.1 (the bundled solr in sunspot is 1.4), and index field location like

class Product < ActiveRecord::Base
  searchable do
    string(:location, :as => :location) { [lat,lng].join(',') }
  end
end

Also the field type needs to be added into schema.xml. (An example, I have not tried it myself)

<types>
  ...
  <fieldType name="geo" class="solr.LatLonType" omitNorms="true"/>
</types>
<fields>
  ...
  <field name="location" stored="false" termVectors="false" type="geo" multiValued="false" indexed="true"/>
</fields>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM