Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails - Elasticsearch completion suggester and search API

I'm using the search API, and now need to add the completion suggester, I'm using elasticsearch-rails gem.

When I search for an article, everything works http://localhost:9200/articles/_search

  "query": {
    "multi_match": {
      "query": "test",
      "fields": [
        "title", "tags", "content"
      ]
    }
  }
}

But since I've implemented the completion suggester I had to edit as_indexed_json to make it work, but now the search API doesn't work anymore, only the suggestions.

Here is my Article model:

  def self.search(query)
    __elasticsearch__.search(
        {
            query: {
                multi_match: {
                    query: query,
                    fields: ['title', 'content', 'tags']
                }
            }
        })
end

      def self.suggest(query)
        Article.__elasticsearch__.client.suggest(:index => Article.index_name, :body => {
            :suggestions => {
                :text => query,
                :completion => {
                    :field => 'suggest'
                }
            }
        })
      end

      def as_indexed_json(options={}) 
       {
            :name => self.title,
            :suggest => {
                :input => self.title,
                :output => self.title,
                :payload => {
                    :content => self.content,
                    :tags => self.tags,
                    :title => self.title
                }
            }
        }.as_json
      end

Is it possible to have _search and _suggest working together with the same model ?

like image 411
user2037696 Avatar asked Mar 05 '15 18:03

user2037696


1 Answers

I'm just digging into elasticsearch, but, as far as i understand, you can add what you had before modifying in the serializer function and recreate indices, they will live together well in the db. For example:

def as_indexed_json(options={}) 
       {
           :name => self.title,
            :suggest => {
                :input => self.title,
                :output => self.title,
                :payload => {
                    :content => self.content,
                    :tags => self.tags,
                    :title => self.title
                }
            }
        }.as_json.merge(self.as_json) # or the customized hash you used

To avoid indices redundancy you can look at aliases and routing.

like image 188
Eugene Petrov Avatar answered Sep 19 '22 10:09

Eugene Petrov