1--首先安装
pip install flask_whooshalchemy
2--修改模型中的定义。
import flask.ext.whooshalchemy
# set the location for the whoosh index
app.config['WHOOSH_BASE'] = 'path/to/whoosh/base'
class Blog(db.Model):
__tablename__ = 'blogpost'
__searchable__ = ['title', 'content'] # these fields will be indexed by whoosh
id = app.db.Column(app.db.Integer, primary_key=True)
title = app.db.Column(app.db.Text)
content = app.db.Column(app.db.Text)
created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
def __repr__(self):
return '{0}(title={1})'.format(self.__class__.__name__, self.title)
3--创建索引。已经有的数据不会创建索引,只对配置好之后的数据创建,因此要想测试出结果,需要先插入数据。
db.session.add(
BlogPost(title='My cool title', content='This is the first post.')
); db.session.commit()
4--检索测试。写一个search方法。
results = Blog.query.whoosh_search(keyword, fields=('title',)).all()