Advanced Ultrasphinx: tags and filters

    On a habr already wrote about Rails integration with the excellent search engine sphinx
    Rails + Sphinx =? Part I
    Rails and Sphinx.
    In this article I will try to talk about additional features of the Ultrasphinx plugin.




    Step # 1: Search by tags



    We take out the following code in the UltrasphinxHelpers module and put it in “lib / ultrasphinx_helpers.rb”:
    We write in the model:
    Copy Source | Copy HTML
    1. is_indexed :fields => ['title',"body"], :include => UltrasphinxHelpers::include_tags_configuration(self)


    Consider the following example:

    Copy Source | Copy HTML
    1. class Article
    2.     belongs_to :user
    3.     is_indexed :fields => ["name","body","user_id"], :include => UltrasphinxHelpers::include_tags_configuration(self)
    4. end
    5.  
    6. Ultrasphinx::Search.new(:query=>"ruby") # будут найдены все записи которые имеют слово "ruby" в поле "name" или "body" или тег "ruby"
    7.  


    If we want to search in only one field:
    Copy Source | Copy HTML
    1. Ultrasphinx::Search.new(:query=>"tag:ruby") #Выдаст только объекты которые затаганы тегом "ruby"
    2. Ultrasphinx::Search.new(:query=>"name:*sphinx") #Будем искать только по имени, найдется все что содержит в имени слова с суффиксом sphinx


    Step # 2: Search Only Among Specific Entries



    And lastly, if we want to search only among the articles of our friends:
    Copy Source | Copy HTML
    1. friends_ids = current_user.friends.map(&:id) #[1,2,5,6,9,12]
    2. Ultrasphinx::Search.new(:query=>"*sphinx",:filters=>{:user_id=> friends_ids})


    _________
    The text is prepared in HabraRedaktor


    Also popular now: