Skip to content

Instantly share code, notes, and snippets.

@zerolab
Created June 18, 2021 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerolab/8161fb93888071e607fb98b436f68034 to your computer and use it in GitHub Desktop.
Save zerolab/8161fb93888071e607fb98b436f68034 to your computer and use it in GitHub Desktop.
RootFilterField in Wagtail -- enables you to index the field without the specific page model string prefix
from wagtail.search.backends.elasticsearch7 import (
Elasticsearch7Mapping,
Elasticsearch7SearchBackend,
Elasticsearch7SearchQueryCompiler,
Elasticsearch7SearchResults,
)
from .index import RootFilterField
class SearchMapping(Elasticsearch7Mapping):
def get_field_mapping(self, field):
name, mapping = super().get_field_mapping(field)
if isinstance(field, RootFilterField):
if mapping["type"] == "string":
mapping["type"] = self.keyword_type
if self.set_index_not_analyzed_on_filter_fields:
# Not required on ES5+ as that uses the "keyword" type for
# filtered string fields
mapping["index"] = "not_analyzed"
mapping["include_in_all"] = False
return name, mapping
def get_field_column_name(self, field):
if isinstance(field, RootFilterField):
return field.get_attname(self.model) + "_filter"
return super().get_field_column_name(field)
class SearchQueryCompiler(Elasticsearch7SearchQueryCompiler):
mapping_class = SearchMapping
class SearchBackend(Elasticsearch7SearchBackend):
mapping_class = SearchMapping
query_compiler_class = SearchQueryCompiler
results_class = Elasticsearch7SearchResults
from wagtail.search.backends.elasticsearch5 import get_model_root
from wagtail.search.index import BaseField
class RootFilterField(BaseField):
def get_definition_model(self, cls):
return get_model_root(cls)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment