Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Enable fuzziness for all Elasticsearch plaintext queries in Wagtail
"""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
@demonshreder
Copy link

demonshreder commented Aug 29, 2020

This helped me out with fuzziness, thanks a lot. Is there anyway to mainline this to the wagtail docs?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment