Last active
January 31, 2017 10:09
-
-
Save shawndeprey/71ab5216906258c768f7 to your computer and use it in GitHub Desktop.
Helper module and class example for type-ahead searching
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
# Model Mapping example | |
# Be sure to replicate this with your actual model | |
class YourModel < ActiveRecord::Base | |
include Elasticsearch::Model | |
include Elasticsearch::Model::Callbacks | |
settings IndexHelper.type_ahead_analysis do | |
mappings do | |
indexes :id, index: :no | |
indexes :screen_name, type: 'string', analyzer: 'autocomplete' | |
end | |
end | |
def as_indexed_json(options = {}) | |
as_json({ only: [:id, :screen_name] }) | |
end | |
def self.search(term, page, per_page) | |
search( | |
query: { | |
match: { | |
screen_name: { query: term } | |
} | |
} | |
).page(page).per_page(per_page).results | |
end | |
end | |
# The Helper Module | |
# Ensure you edit the indexing helper function | |
module IndexHelper | |
def self.type_ahead_analysis | |
{ | |
index: { | |
number_of_shards: 1, | |
number_of_replicas: 0, | |
analysis: { | |
filter: { | |
autocomplete_filter: { | |
type: 'edge_ngram', | |
min_gram: 1, | |
max_gram: 20 | |
} | |
}, | |
analyzer: { | |
autocomplete: { | |
type: 'custom', | |
tokenizer: 'standard', | |
filter: [ | |
'lowercase', | |
'autocomplete_filter' | |
] | |
} | |
} | |
} | |
} | |
} | |
end | |
# MUST EDIT | |
# Ensure that you replace 'your_models' & 'YourModel' below with whatever your model actually is | |
def self.index_your_model | |
puts 'Deleting your_models index...' | |
Elasticsearch::Client.new.indices.delete index: 'your_models' rescue nil | |
puts 'Creating your_models index and importing all your_models...' | |
YourModel.import force: true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment