Skip to content

Instantly share code, notes, and snippets.

@jkostolansky
Last active October 6, 2022 19:31
Show Gist options
  • Save jkostolansky/0d629ac3ef1a7e74c21413f51fe9cd48 to your computer and use it in GitHub Desktop.
Save jkostolansky/0d629ac3ef1a7e74c21413f51fe9cd48 to your computer and use it in GitHub Desktop.
Chewy multi-index search
Chewy.filter :chewy_ngram,
type: 'edge_ngram',
min_gram: 1,
max_gram: 50
Chewy.analyzer :chewy_fulltext_search,
type: 'custom',
tokenizer: 'standard',
filter: %w[lowercase asciifolding chewy_ngram]
class GlobalSearch
def self.search(query)
index_classes = [UsersIndex, ProductsIndex]
bool_queries = index_classes.map do |index_class|
{
bool: {
filter: [
{ term: { _index: index_class.global_search_fields } }
]),
must: {
multi_match: {
query: query,
fields: index_class.global_search_fields
}
}
}
}
end
index_classes[0].indices(*index_classes[1..]).query(
bool: { should: bool_queries }
)
end
end
class ProductsIndex < Chewy::Index
settings analysis: {
analyzer: %w[chewy_fulltext_search]
}
index_scope Product
field :title, type: 'text', analyzer: 'chewy_fulltext_search'
field :brand, type: 'text', analyzer: 'chewy_fulltext_search'
field :description, type: 'text', analyzer: 'chewy_fulltext_search'
field :updated_at, type: 'date'
def self.global_search_fields
%w[title brand description]
end
end
class UsersIndex < Chewy::Index
settings analysis: {
analyzer: %w[chewy_fulltext_search]
}
index_scope User.active
field :username, type: 'text', analyzer: 'chewy_fulltext_search'
field :name, type: 'text', analyzer: 'chewy_fulltext_search'
field :bio, type: 'text', analyzer: 'chewy_fulltext_search'
field :updated_at, type: 'date'
def self.global_search_fields
%w[username name bio]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment