我正在运行django-haystack v2.0.0与 pyelasticsearch v0.3在我的一个项目中。我有一个 SearchView
呈现一个列表模板,我想集成结果过滤。搜索运行良好,但我使用的过滤器根本不起作用?我使用以下过滤器 __contains
, __lte
, __gte
但它们似乎都没有对结果列表产生影响。
比如说,我有 10 个结果来自 SearchView
基于搜索词。在同一个模板上,我有一个过滤器表单(使用 GET
方法)并调用相同的 SearchView
.现在在 SearchView 下我有一个自定义的私有(private) _filter_results
方法定义如下。
def _filter_results(results, filters):
"""
This method would return the filtered search results, based on
the filters applied by a user.
"""
for item in filters:
if item == 'location':
results = results.filter(locations__contains=filters[item])
print results
if item == 'age_min':
results = results.filter(workex_min__gte=filters[item])
if item == 'age_max':
results = results.filter(workex_max__lte=filters[item])
return results
现在,我将结果传递给模板,如下所示:
context {'results' : _filter_results(self.results, self.result_filters)}
self.result_filters
是我在 SearchView
中设置的过滤器字典的__call__
方法,它看起来像这样。{
'location' : request.GET.get('location'),
'age_min' : request.GET.get('age_min'),
'age_max' : request.GET.get('age_max'),
}
我没有收到任何错误,并且我仔细检查了每个过滤器值是否被传递给
_filter_results
方法。但结果仍然保持不变。如果在 10 个条目的结果列表中,我尝试使用其中没有一个条目包含该位置的位置进行过滤,我仍然会得到相同 10 个条目的结果。可能是什么原因 ?
最佳答案
我没有将 Haystack 与 ElasticSearch 一起使用,但已在 Solr 中广泛使用它,但它也应该与 ElasticSearch 相同。
您应该使用 results.narrow() 方法而不是过滤器。 Filter 方法本质上将在过滤器中附加主要的初始查询词,并在它们之间运行“OR”查询,因为默认运算符在 haystack 中设置为“OR”。
窄() 方法专门用于过滤初始结果集并进一步细化它们,这也有利于使用窄运行过滤查询,因为在搜索引擎中构造的查询是不同的,并且可以更好地利用内置缓存。
def _filter_results(results, filters):
"""
This method would return the filtered search results, based on
the filters applied by a user.
"""
for item in filters:
if item == 'location':
results = results.narrow('locations:%s' % filters[item])
print results
if item == 'age_min':
results = results.narrow('workex_min:[%s TO *]' % filters[item])
if item == 'age_max':
results = results.narrow('workex_max:[* TO %s]' % filters[item])
return results
这也是它与 Solr 一起工作的方式,但是 haystack 方法的概念是相同的,唯一的区别在于每个 SearchEngine 的后端文件。您应该查看 haystack/backends/elasticsearch_backend.py 以获得更好的理解。
也看看 FacetedSearchView 和 FacetedSearchForm
关于django - 搜索查询集的 __contains 过滤器有用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14276043/