2016-09-27 118 views
0

我目前正在使用elasticsearch通過名稱查找客戶端,如果輸入完整名稱,它會起作用。但是,即使客戶只輸入名稱的前兩個字母,我也需要能夠搜索。我試圖使用部分匹配,但我得到這個錯誤。部分匹配elasticsearch rails

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} 

我的模型/廣告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 

任何想法,爲什麼?

回答

-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

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

+0

謝謝!這解決了這個問題,但仍然無法讓它做一個部分匹配。 –

+0

你在用什麼查詢?你可以發佈你的方法嗎? – davide

+0

順便說一句,如果你想與第一個輸入字符匹配,我最好使用'edge_ngram'過濾器。見https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-edgengram-tokenizer.html – davide