rails - Elasticsearch完成建议器和搜索API

时间:2015-03-05 18:05:26

标签: ruby-on-rails autocomplete elasticsearch

我正在使用搜索API,现在需要添加completion suggester,我正在使用elasticsearch-rails gem。

当我搜索文章时,一切正常 http://localhost:9200/articles/_search

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

但是,由于我已经实现了完成建议,我必须编辑as_indexed_json才能使其正常工作,但现在搜索API不再有效,只有建议。

这是我的文章模型:

  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

是否可以让_search和_suggest与同一模型一起工作?

1 个答案:

答案 0 :(得分:5)

我只是深入研究elasticsearch,但据我所知,您可以在序列化程序功能中修改之前添加您所拥有的内容并重新创建索引,它们将在数据库中很好地共存。例如:

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

为避免索引冗余,您可以查看aliases and routing