Flask-WhooshAlchemy: 搜索'not
我刚刚完成了Flask超大教程中关于使用Flask-WhooshAlchemy实现全文搜索的部分(可以查看这个链接:http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-x-full-text-search),现在我有以下的帖子:
>>> Post.query.whoosh_search('fourth').all()
[Post u'not my fourth', Post u'my fourth and last post']
我尝试使用 Post.query.whoosh_search('fourth AND not').all()
,希望能得到 [Post u'not my fourth']
作为结果,但实际上我得到了原来的两个帖子。
我该怎么做才能让WhooshAlchemy把 not
当作一个字符串来处理,而不是当作一个操作符呢?
2 个回答
0
我已经重现了你的设置。
>>> Post.query.whoosh_search('fourth not').all()
>>> [<Post u'not my fourth'>, <Post u'my fourth and last post'>]
你应该问的问题是:为什么whoosh_search找不到“not”?试试这个。
>>> Post.query.whoosh_search('not').all()
>>> []
这应该返回帖子“not my fourth”,对吧?
根据这份文档中的“停用词”部分,“停用词”是指那些太常见的词,索引它们往往没有意义。这个问题中有个链接显示,默认情况下“not”是一个停用词,而whoosh_search并不会对它进行索引。
所以我们再添加一个包含“fourth”和一个不太常见的词——比如“cheese”的帖子。
>>> p = Post(body='cheese is the fourth food group', timestamp=datetime.datetime.utcnow(), author=u)
>>> db.session.add(p)
>>> db.session.commit()
现在我们来搜索所有包含“fourth”和“cheese”的帖子。
>>> Post.query.whoosh_search('fourth cheese').all()
>>> [<Post u'cheese is the fourth food group'>]
太好了。
附加内容:如果你想获取所有包含“fourth”或“cheese”的帖子,可以这样做:
>>> Post.query.whoosh_search('cheese fourth', or_=True).all()
>>> [<Post u'cheese is the fourth food group'>, <Post u'not my fourth'>, <Post u'my fourth and last post'>]
0
根据这页最后一段内容,在Flask-WhooshAlchemy 的文档中,查询的关键词默认是以“与”的方式处理的。所以你可以把你的搜索改成
Post.query.whoosh_search("fourth not").all()
如果你还是遇到问题,可能需要这样做
Post.query.whoosh_search("fourth AND 'not'").all()
具体可以参考Whoosh 关于如何从文字生成查询词的文档。