Search code examples
ruby-on-railsruby-on-rails-5sphinxthinking-sphinx

Searching in polygons in sphinx using Thinking Sphinx


I have setup thinking sphinx for real-time indexing and It works very well and search with geodist as well.But now I want to search the records within polygon.

Sphinx documentation explains it very well at Geo-distance searching

now I want to use this functionality using thinking sphinx. Thinking sphinx does explain about geodist search Here But It does not state how to search within a polygon.

Can any one help me here to do that?


Solution

  • Thinking Sphinx doesn't have anything inbuilt to provide a neat interface for the polygon searching, but it's certainly possible to use the functionality.

    You'll want to generate the SphinxQL SELECT clause that you'd like, filter on it accordingly, and/or you can access your custom attributes using the AttributesPane. The following code is hopefully clear:

    search = Model.search("foo",
      :select => "*, CONTAINS(GEOPOLY2D(...), ...) AS inside",
      :with   => {:inside => true}
    ); ""
    search.context[:panes] << ThinkingSphinx::Panes::AttributesPane
    search.collect { |instance| instance.sphinx_attributes["inside"] }
    

    The ; "" at the end of the first statement is only needed when running this in IRB or a Rails console - you want to avoid calling search in a way that evaluates the results until you've added the pane in. Search results are normally lazily loaded, but IRB calls inspect to print statement results which removes the lazy advantage.

    Panes are discussed in a blog post I wrote, and the source code for the AttributesPane class is very simple. You may also want to write a custom middleware class that uses your own options and translates them into the polygon functions - the Geographer class (which is what translates :geo into GEODIST) is a good reference for that.