Last active
October 6, 2022 19:31
-
-
Save jkostolansky/0d629ac3ef1a7e74c21413f51fe9cd48 to your computer and use it in GitHub Desktop.
Chewy multi-index search
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
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] |
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
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 |
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
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 |
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
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