flask 的全文搜索插件很少,有个Flask-WhooshAlchemy,最近发现个flask-msearch,使用了下感觉不错。
安装flask-msearch
pip install flask-msearch
flask配置
from flask_msearch import Search
...
search = Search()
search.init_app(app)
#如果出现“sqlalchemy ValueError”报错,那么修改为
#db = SQLalchemy()
#search = Search(db=db)
# 修改models.py
class Post(db.Model):
__tablename__ = ‘post‘
__searchable__ = [‘title‘, ‘content‘] #指定要索引的字段
# 修改views.py
@app.route("/search")
def w_search():keyword = request.args.get(‘keyword‘)
results = Post.query.msearch(keyword,fields=[‘title‘],limit=20).filter(...)
# 或者results = Post.query.filter(...).msearch(keyword,fields=[‘title‘],limit=20).filter(...)
return ‘‘
Configure
MSEARCH_INDEX_NAME = ‘whoosh_index‘
# simple,whoosh
MSEARCH_BACKEND = ‘whoosh‘
# 自动生成或更新索引
MSEARCH_ENABLE = True
Usage
创建更新删除索引
如果要对已存在的数据创建索引(全部)
# 创建
search.create_index()
# 更新
search.create_index(update=True)
# 删除
search.create_index(delete=True)
如果只想要为指定的表创建索引
search.create_index(Model)
自定义analyzer
比如使用jieba的中文分词
from jieba.analyseimportChineseAnalyzer
search = Search(analyzer=ChineseAnalyzer())
项目地址:https://github.com/honmaple/flask-msearch