How can I do a fuzzy search using django-haystack and the elasticsearch backend?

喜欢而已 提交于 2019-12-10 03:26:26

问题


It looks as if elasticsearch supports fuzzy queries (http://www.elasticsearch.org/guide/reference/query-dsl/fuzzy-query/) but I can't figure out a way to have django-haystack pass in that option.

I dug into the django-haystack search and it looks as if it's using the 'match_all' query when using the elasticsearch backend. Is it possible to get the fuzzy match behavior without having to modify the django-haystack source code?

Haystack Source: https://github.com/toastdriven/django-haystack/blob/master/haystack/backends/elasticsearch_backend.py (the build_search_kwargs method is what I suspect I need to change)


回答1:


No need to fork Haystack, you can update that method in your own backend (for more details, see Stretching Haystack's ElasticSearch Backend). The build_search_kwargs method returns a dictionary so you can just modify the original return value.

Disclaimer: this code is just an example of how you could update your own backend, not how to implement fuzzy search.

class FuzzyBackend(ElasticsearchSearchBackend):
    def build_search_kwargs(self, query_string, **kwargs):
        fuzzy = kwargs.pop('fuzzy', False)
        fuzzy_field = kwargs.pop('min_similarity', '')
        search_kwargs = super(FuzzyBackend, self).build_search_kwargs(
                query_string, kwargs)
        if fuzzy:
            search_kwargs = {'fuzzy': {fuzzy_field: query_string}}
        return search_kwargs


来源:https://stackoverflow.com/questions/18000714/how-can-i-do-a-fuzzy-search-using-django-haystack-and-the-elasticsearch-backend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!