Skip to content

Instantly share code, notes, and snippets.

@mihow
Last active April 7, 2021 10:56
Show Gist options
  • Select an option

  • Save mihow/5e96b1ef8d4d78f0577dfae83cd77588 to your computer and use it in GitHub Desktop.

Select an option

Save mihow/5e96b1ef8d4d78f0577dfae83cd77588 to your computer and use it in GitHub Desktop.

Revisions

  1. mihow revised this gist Jan 8, 2019. No changes.
  2. mihow created this gist Jan 8, 2019.
    32 changes: 32 additions & 0 deletions elasticsearch6_fuzzy.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    """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