Last active
April 7, 2021 10:56
-
-
Save mihow/5e96b1ef8d4d78f0577dfae83cd77588 to your computer and use it in GitHub Desktop.
Enable fuzziness for all Elasticsearch plaintext queries in Wagtail
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
"""Elasticsearch backend that enables fuzzy search to all plaintext queries.""" | |
from wagtail.search.backends.elasticsearch6 import (Elasticsearch6SearchBackend, | |
Elasticsearch6SearchQueryCompiler) | |
class ElasticsearchQueryCompilerWithFuzziness(Elasticsearch6SearchQueryCompiler): | |
""" | |
Copy of Elasticsearch6SearchQueryCompiler class with a modified default query. | |
Adds the "fuzziness" parameter to all queries so that we can return inexact | |
matches for misspellings, etc. | |
Elasticsearch docs on fuzziness: | |
https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#fuzziness | |
""" | |
def _compile_plaintext_query(self, *args, **kwargs): # pylint: disable=W0221 | |
"""Add the `fuzziness` parameter to all `match` & `match_multi` queries.""" | |
query = super()._compile_plaintext_query(*args, **kwargs) | |
# The query is a dictionary with one key for the query type. | |
# Either "match" or "match_multi" | |
query_type = list(query.keys())[0] | |
query[query_type]['fuzziness'] = 'AUTO' | |
return query | |
class CustomSearchBackend(Elasticsearch6SearchBackend): | |
"""Copy of the Elasticsearch6SearchBackend with a custom query class.""" | |
query_compiler_class = ElasticsearchQueryCompilerWithFuzziness | |
SearchBackend = CustomSearchBackend |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This helped me out with fuzziness, thanks a lot. Is there anyway to mainline this to the wagtail docs?