From 25da9fb81ecec8230a6a4d80688dd82230414e55 Mon Sep 17 00:00:00 2001 From: Matt Westcott Date: Thu, 15 Feb 2024 12:38:30 +0000 Subject: [PATCH] Fix empty admin search on Elasticsearch (backport to 5.2) Backport of #11626 to 5.2; fixes #11600 --- wagtail/search/backends/elasticsearch5.py | 11 ++++++-- .../tests/test_elasticsearch5_backend.py | 25 +++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/wagtail/search/backends/elasticsearch5.py b/wagtail/search/backends/elasticsearch5.py index 5cacb71ea1..7fefb1f9b5 100644 --- a/wagtail/search/backends/elasticsearch5.py +++ b/wagtail/search/backends/elasticsearch5.py @@ -653,8 +653,15 @@ class ElasticsearchAutocompleteQueryCompilerImpl: if len(fields) == 0: # No fields. Return a query that'll match nothing return {"bool": {"mustNot": {"match_all": {}}}} - - return self._compile_plaintext_query(self.query, fields) + elif isinstance(self.query, PlainText): + return self._compile_plaintext_query(self.query, fields) + elif isinstance(self.query, MatchAll): + return {"match_all": {}} + else: + raise NotImplementedError( + "`%s` is not supported for autocomplete queries." + % self.query.__class__.__name__ + ) class Elasticsearch5AutocompleteQueryCompiler( diff --git a/wagtail/search/tests/test_elasticsearch5_backend.py b/wagtail/search/tests/test_elasticsearch5_backend.py index b8cd681ced..23fc913d20 100644 --- a/wagtail/search/tests/test_elasticsearch5_backend.py +++ b/wagtail/search/tests/test_elasticsearch5_backend.py @@ -70,6 +70,31 @@ class TestElasticsearch5SearchQuery(TestCase): } self.assertDictEqual(query_compiler.get_query(), expected_result) + def test_match_all_autocomplete(self): + # Create a query + query = self.autocomplete_query_compiler_class( + models.Book.objects.all(), MATCH_ALL + ) + + # Check it + expected_result = { + "bool": { + "filter": {"match": {"content_type": "searchtests.Book"}}, + "must": {"match_all": {}}, + } + } + self.assertDictEqual(query.get_query(), expected_result) + + def test_non_supported_queries_autocomplete(self): + # Create a query + query = self.autocomplete_query_compiler_class( + models.Book.objects.all(), Fuzzy("Hello") + ) + + # Check it + with self.assertRaises(NotImplementedError): + query.get_query() + def test_match_all(self): # Create a query query_compiler = self.query_compiler_class(models.Book.objects.all(), MATCH_ALL)