try:
    # Wagtail 7.2+ delegates search backends to django-modelsearch.
    from modelsearch.backends.elasticsearchbase import Field
except ImportError:  # pragma: no cover
    # Wagtail <= 7.1 ships its own Elasticsearch backends and defines Field there.
    from wagtail.search.backends.elasticsearch7 import Field
from wagtail.search.backends.elasticsearch8 import (
    Elasticsearch8SearchBackend as BaseElasticsearch8SearchBackend,
)
from wagtail.search.backends.elasticsearch8 import (
    Elasticsearch8SearchQueryCompiler as BaseElasticsearch8SearchQueryCompiler,
)


class Elasticsearch8SearchQueryCompiler(BaseElasticsearch8SearchQueryCompiler):
    def _remap_fields(self, fields):
        remapped_fields = super()._remap_fields(fields)

        if fields:
            remapped_fields.append(Field(self.mapping.all_field_name))

        return remapped_fields


class Elasticsearch8SearchBackend(BaseElasticsearch8SearchBackend):
    query_compiler_class = Elasticsearch8SearchQueryCompiler


SearchBackend = Elasticsearch8SearchBackend
