Skip to content

Instantly share code, notes, and snippets.

@krzykamil
Created February 10, 2018 17:44
Show Gist options
  • Save krzykamil/0cd7963c5c66e6ba126fcecc9cdfcec1 to your computer and use it in GitHub Desktop.
Save krzykamil/0cd7963c5c66e6ba126fcecc9cdfcec1 to your computer and use it in GitHub Desktop.
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