我希望ElasticSearch(特定的Tire gem)根据关键字在字段中出现的次数返回结果.例如,我在名为Article的模型中索引字段标题.我有两个对象,第一个对象的标题值为“Funny Funny subject”,而第二个对象的标题值为“Funny subject”.我想以这样的方式索引,如果我搜索关键字’Funny’,第一个对象将首先返回,因为它在标题中出现了两个’Funny’字样.是否可以通过轮胎来做到这一点?什么是索引方法? 最佳答案 这里是一个工作示例,这里的关键因素是boostvalue必须足够高并且您不能在查询中使用Wildcharts.
require 'tire'
require 'yajl/json_gem'
articles = [
{ :id => '0', :type => 'article', :title => 'nothing funny'},
{ :id => '1', :type => 'article', :title => 'funny'},
{ :id => '2', :type => 'article', :title => 'funny funny funny'}
]
Tire.index 'articles' do
import articles
end
Tire.index 'articles' do
delete
create :mappings => {
:article => {
:properties => {
:id => { :type => 'string', :index => 'not_analyzed', :include_in_all => false },
:title => { :type => 'string', :boost => 50.0, :analyzer => 'snowball' },
:tags => { :type => 'string', :analyzer => 'keyword' },
:content => { :type => 'string', :analyzer => 'snowball' }
}
}
}
import articles do |documents|
documents.map { |document| document.update(:title => document[:title].downcase) }
end
refresh
end
s = Tire.search('articles') do
query do
string "title:funny"
end
end
s.results.each do |document|
puts "* id:#{ document.id } #{ document.title } score: #{document._score}"
end
给
* id:2 funny funny funny score: 14.881571
* id:1 funny score: 14.728935
* id:0 nothing funny score: 9.81929