[英]elasticsearch-rails how to write query for search
我正在使用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
我收到了搜索结果。 但我的问题是:如果我搜索“约翰队”。
Articles.search('John team').records.records
我得到了多个完美匹配'john队'的记录和一些与'john'或'team'相关的比赛。
但我想,如果'john team'在我的数据库中完全匹配,结果应该只有john team.I不想要其他记录。但是如果'john team'不存在我想要另一个与'john'或'相关的结果团队'两个关键词。
例:
Article.search('John team').records.records
responce: ('john team', 'team joy', 'John cena')
但我想要
Article.search('John team').records.records
responce: ('john team')
如果您想要匹配单词而不是任何单个单词,请尝试此操作
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: {},
}
}
}
)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.