📜 ⬆️ ⬇️

Advanced Ultrasphinx: tags and filters

On Habré already wrote about the integration of Rails with a great search engine sphinx
Rails + Sphinx =? Part I
Rails and Sphinx.
In this article I will try to talk about the 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”:
In the model we write:
Copy Source | Copy HTML is_indexed :fields => [ 'title' ,"body"], : include => UltrasphinxHelpers::include_tags_configuration(self)
  1. Copy Source | Copy HTML 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. Ultrasphinx :: Search . new (: query => "ruby") # all entries that have the word "ruby" in the "name" or "body" field or the "ruby" tag will be found


If we want to search only in one field:
Copy Source | Copy HTML
  1. Ultrasphinx :: Search . new (: query => "tag: ruby") # Displays only objects that are tagged with "ruby"
  2. Ultrasphinx :: Search . new (: query => "name: * sphinx") # We will search only by name, there is everything that contains in the name words with the suffix sphinx


Step 2: Search only among certain 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 was prepared in Habra Editor

Source: https://habr.com/ru/post/54636/


All Articles