Created
February 10, 2018 17:44
-
-
Save krzykamil/0cd7963c5c66e6ba126fcecc9cdfcec1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'elasticsearch/model' | |
module Concerns | |
module Author | |
module Searchable | |
extend ActiveSupport::Concern | |
included do | |
include Elasticsearch::Model | |
include Elasticsearch::Model::Callbacks | |
settings index: { number_of_shards: 1 } do | |
mappings dynamic: 'false' do | |
indexes :name, type: 'text' | |
indexes :alias, type: 'text' | |
end | |
end | |
def as_indexed_json(_options = {}) | |
{ | |
name: name, | |
alias: alias | |
} | |
end | |
def self.search(query) | |
__elasticsearch__.search( | |
query: { | |
bool: { | |
should: [ | |
{ match: { name: { query: cleaned_query(query), boost: 2 } } }, | |
{ match: { alias: { query: cleaned_query(query) } } } | |
] | |
} | |
} | |
) | |
end | |
def self.cleaned_query(query) | |
escaped_characters = Regexp.escape('\\+-&|!(){}[]^~*?:\/') | |
query.gsub(/([#{escaped_characters}])/, '\\\\\1') | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment