如何使用django-haystack和elasticsearch后端进行模糊搜索?

时间:2022-11-03 19:34:51

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.

看起来好像有弹性搜索支持模糊查询(http://www.elasticsearch.org/guide/reference/query-dsl/fuzzy-query/),但我无法找到让django-haystack通过该选项的方法。

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?

我挖到了django-haystack搜索,看起来好像在使用elasticsearch后端时使用'match_all'查询。是否有可能在不必修改django-haystack源代码的情况下获得模糊匹配行为?

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)

Haystack来源:https://github.com/toastdriven/django-haystack/blob/master/haystack/backends/elasticsearch_backend.py(build_search_kwargs方法是我怀疑我需要更改的方法)

1 个解决方案

#1


6  

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.

无需分叉Haystack,您可以在自己的后端更新该方法(有关更多详细信息,请参阅扩展Haystack的ElasticSearch后端)。 build_search_kwargs方法返回一个字典,因此您只需修改原始返回值即可。

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

#1


6  

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.

无需分叉Haystack,您可以在自己的后端更新该方法(有关更多详细信息,请参阅扩展Haystack的ElasticSearch后端)。 build_search_kwargs方法返回一个字典,因此您只需修改原始返回值即可。

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