I am using elasticsearch-rails and elasticsearch-model gem for searching words in my rails app.
Here is my model article.rb where I want to search to take place:
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
Here is my model controller 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
I am getting search results. But my question is : If I search for "John team".
Articles.search('John team').records.records
I get multiple records with perfect match 'john team' and some matches related to 'john' or 'team'.
but I want , if 'john team' is perfectly match in my database the result should only john team.I don't want another records.but if 'john team' is not present I want another results related to 'john' or 'team' both keywords.
example:
Article.search('John team').records.records
responce: ('john team', 'team joy', 'John cena')
But I want
Article.search('John team').records.records
responce: ('john team')
Try this if you want to match both the words and not any single word
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.