Django“你是指?”查询

3

我正在编写一个相对简单的Django应用程序,用户可以输入字符串查询。该应用程序将搜索数据库以查找此字符串。

Entry.objects.filter(headline__contains=query)

这个查询非常简单,但对于不确定自己在寻找什么的人来说并不是很有帮助。因此,我扩展了搜索范围。

from django.utils import stopwords

results = Entry.objects.filter(headline__contains=query)
if(!results):
    query = strip_stopwords(query)
    for(q in query.split(' ')):
        results += Entry.objects.filter(headline__contains=q)

我希望为此添加一些额外的功能,例如搜索拼写错误、复数形式、常见同音异形词等。我只是想知道Django的查询语言中是否内置了这些功能。对于我来说,这并不重要,因为我只是在寻找一些内置的东西,而不是编写一个庞大的算法。
谢谢您提前提供的所有答案。

你正在寻找一个“Soundex”搜索算法:http://en.wikipedia.org/wiki/Soundex - Jon Limjap
1
嗯... Soundex 最初是用来捕捉英语姓氏的文书错误的。它在一般词汇中的使用不太有用。 - Peter Rowell
3个回答

11
你可以尝试使用Python的difflib模块。
>>> from difflib import get_close_matches
>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape']
>>> import keyword
>>> get_close_matches('wheel', keyword.kwlist)
['while']
>>> get_close_matches('apple', keyword.kwlist)
[]
>>> get_close_matches('accept', keyword.kwlist)
['except']

问题在于使用difflib需要从数据库构建单词列表,这可能很昂贵。也许如果您缓存单词列表并只偶尔重新构建它,会更好一些。
一些数据库系统支持搜索方法以实现您想要的功能,例如PostgreSQL的fuzzystrmatch模块。如果您的情况是这样的,可以尝试调用它。

编辑:

针对你的新“需求”,很抱歉,你没有运气。不,django的查询语言内部没有任何内置功能。


5

djangos orm没有这个功能,但是有几个项目将django与搜索服务集成在一起,例如:

我不知道选项#2和#3的表现如何,但我经常使用django-sphinx,并对结果非常满意。


0
cal_name = request.data['column']['name']

        words = []
        for col in Column.objects.all():
            if cal_name != col.name:
                words.append(col.name)
        words = difflib.get_close_matches(cal_name, words)
        if len(words) > 0 and is_sure != "true":
            return Response({
                'potential typo': 'Did you mean ' + str(words) + '?',
                "note": "If you think you do not have a typo send {'sure' : 'true'} with the data."})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接