Django haystack自动完成无法正常工作

时间:2012-05-23 10:40:48

标签: autocomplete django-haystack whoosh

我在Django 1.4中使用haystack 1.2.7 + whoosh 2.4.0(Python是2.7)

我的设置:

HAYSTACK_SITECONF = 'verticalsoftware.search.search_sites'
HAYSTACK_SEARCH_ENGINE = 'whoosh'
HAYSTACK_WHOOSH_PATH = 'C:/whoosh/prodeo_index'
HAYSTACK_INCLUDE_SPELLING = True

搜索索引:

class GalleryIndex(SearchIndex):
    text = indexes.CharField(document=True, use_template=True)
    content_auto = indexes.NgramField(model_attr='title') 
    def index_queryset(self):
        """Used when the entire index for model is updated."""
        return Gallery.objects.filter(date_added__lte=datetime.datetime.now())

还尝试使用EdgeNgramField和/或RealTimeSearchIndex

自定义urlCONF:

from django.conf.urls.defaults import *
from verticalsoftware.search.views import SearchWithRequest

urlpatterns = patterns('haystack.views',
    url(r'^$', SearchWithRequest(), name='haystack_search'), 
)

自定义视图:

from haystack.views import SearchView
import operator
from haystack.query import SearchQuerySet, SQ

class SearchWithRequest(SearchView):

    __name__ = 'SearchWithRequest'

    def build_form(self, form_kwargs=None):
        if form_kwargs is None:
            form_kwargs = {}

        if self.searchqueryset is None:
            sqs = SearchQuerySet().filter(reduce(operator.__or__, [SQ(text=word.strip()) for word in self.request.GET.get("q").split(' ')]))
            form_kwargs['searchqueryset'] = sqs

        return super(SearchWithRequest, self).build_form(form_kwargs)

对于sqs我已经尝试了所有可以想象的东西,使用过滤器和自动完成功能,如文档中所示,以及我能找到的每个相关论坛帖子;将__startswith和__contains与我的content_auto或文本字段结合使用根本没有帮助(后者根本不匹配任何内容;前者只匹配1个字符或完整字符串)

上面粘贴的变体至少具有返回带空格的字符串结果的好处(每个单词仍然必须完全匹配相应的数据库条目,因此需要此帖子)

任何帮助都将非常感谢

1 个答案:

答案 0 :(得分:0)

晚些时候参加聚会,但是建议将您的主文档字段(文本)更改为EdgeNgramFieldNgramField,否则搜索的索引无法匹配单词片段,只有完全单词匹配才可以CharField可以实现。

此外,调试干草堆时,在django shell中播放有时会很有用:

./manage.py shell
from haystack.query import SearchQuerySet
s = SearchQuerySet()
s.auto_query('sear')
s.auto_query('sear').count()
...

相关问题