我正在使用elasticsearch-rails和elasticsearch-model gem在我的rails应用程序中搜索单词。
下面是我想要搜索的模型article.rb:
require 'elasticsearch/model'
class Article < ActiveRecord::Base
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
def self.search(query)
__elasticsearch__.search(
{
query: {
multi_match: {
query: query,
fuzziness: 2,
fields: ['title^10', 'text']
}
},
highlight: {
pre_tags: ['<em>'],
post_tags: ['</em>'],
fields: {
title: {},
}
}
}
)
end
end这是我的模型控制器search_controller.rb
class SearchController < ApplicationController
def search
if params[:q].nil?
@articles = []
else
@articles = Article.search params[:q]
logger.info "LocationController.add_locations called with params: #{@articles.records.each_with_hit { |record, hit| puts "* #{record.title}: #{hit._score}" }}"
end
end
end我正在获取搜索结果。但我的问题是:如果我搜索"John team“。
Articles.search('John team').records.records我得到了多个完美匹配'john team‘的记录,以及一些与'john’或'team‘相关的匹配。
但是我想,如果‘约翰团队’在我的数据库中完美匹配,结果应该只有约翰团队。我不想要另一个records.but,如果‘约翰团队’不存在,我想要另一个与‘约翰’或‘团队’两个关键字相关的结果。
示例:
Article.search('John team').records.records
responce: ('john team', 'team joy', 'John cena')但我想
Article.search('John team').records.records
responce: ('john team')发布于 2017-02-06 20:57:50
如果您想要匹配两个单词而不是任何单个单词,请尝试此操作
def self.search(query)
__elasticsearch__.search(
{
query: {
multi_match: {
query:{ match: {content: {query: query, operator: "and" }}},
fuzziness: 2,
fields: ['title^10', 'text']
}
},
highlight: {
pre_tags: ['<em>'],
post_tags: ['</em>'],
fields: {
title: {},
}
}
}
)
endhttps://stackoverflow.com/questions/42068072
复制相似问题