部分匹配elasticsearch rails

时间:2016-09-27 21:52:41

标签: ruby-on-rails elasticsearch

我目前正在使用elasticsearch按名称查找客户端,如果您输入整个名称,它就可以使用。但是,即使客户只输入了名字的前两个字母,我也需要能够搜索。我试图使用部分匹配,但我收到此错误。

AdGroup.__elasticsearch__.create_index!  force:true
[!!!] Index does not exist (Elasticsearch::Transport::Transport::Errors::NotFound)
Elasticsearch::Transport::Transport::Errors::BadRequest: [400] {"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"analyzer on field 
[client_name] must be set when search_analyzer is 
set"}],"type":"mapper_parsing_exception","reason":"Failed to parse   
mapping [ad_group]: analyzer on field [client_name] must be set when 
 search_analyzer is set","caused_by":{"type":"mapper_parsing_exception","reason":"analyzer on field [client_name] must be set when search_analyzer is set"}},"status":400}

我的模特/ ad-group.rb

class AdGroup < ActiveRecord::Base
   include Elasticsearch::Model
   include Elasticsearch::Model::Callbacks

 settings analysis: {
  filter: {
    ngram_filter: { type: "nGram", min_gram: 2, max_gram: 12 }
  },
  analyzer: {
        index_ngram_analyzer: {
            type: 'custom',
            tokenizer: 'standard',
            filter: ['lowercase', 'ngram_filter']
        },
        search_ngram_analyzer: {
            type: 'custom',
            tokenizer: 'standard',
            filter: ['lowercase']
        }
    }
} do
mapping do 
    indexes :published
    indexes :client_name,:type => "string", index_analyzer:   "index_ngram_analyzer", search_analyzer: "search_ngram_analyzer"
    indexes :created_at
    indexes :updated_at
    indexes :preview_updated_at
end
end

控制器/广告组

class AdGroupsController < ApplicationController
    def index
      if params[:client_name]
       @ad_groups = AdGroup.search(params[:client_name]).page(params[:page]).results
      else
          @ad_groups = AdGroup.includes(:client).where(is_template: false).paginate(:page =>  params[:page]).order('id DESC')
      end

    end
end

知道为什么吗?

2 个答案:

答案 0 :(得分:1)

问题是您要定义search_analyzerindex_analyzer,而不是默认analyzer。看看documentation

如果您修改将client_name的分析器设置为:

的代码行,它将起作用
    indexes :client_name,:type => "string", analyzer:   "index_ngram_analyzer", search_analyzer: "search_ngram_analyzer"

通过这种方式,它将在索引时采用默认analyzer,而在查询时将获取search_analyzer

答案 1 :(得分:-1)

我不确定这会有多大帮助,但我不得不为希望能够搜索商家的客户处理这个问题。这是一年多以前所以我不记得细节,但我必须在business_profiles_controller.rb进行这一改变。

def index
  if params[:query].present?
    @business_profiles = BusinessProfile.search(params[:query], fields: [{ name: :word_middle }])
  else
    @business_profiles = BusinessProfile.all
  end
end

标记:word_middle允许我们在:name字段内搜索每个商家资料。

我希望这有一些帮助。

Using SearchKick and ElasticSearch in Rails 4