Table of Contents
flask 貌似很少全文搜索的插件,有一个 https://github.com/gyllstromk/Flask-WhooshAlchemy , 但试了几次都用不了,所以参考 Flask-WhooshAlchemy 自己写了一个
Quickstart
插件基于 whoosh,纯 python 编写,使用上很简单
from flask_msearch import Search [...] search = Search() search.init_app(app) # 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 = search.whoosh_search(Post,query=keyword,fields=['title'],limit=20) return ''
Usage
创建更新删除索引
如果要对已存在的数据创建索引(全部)
# 创建 search.create_index() # 更新 search.create_index(update=True) # 删除 search.create_index(delete=True)
如果只想要为指定的表创建索引
search.create_index(Model)
自定义analyzer
比如使用jieba的中文分词
from jieba.analyse import ChineseAnalyzer search = Search(analyzer=ChineseAnalyzer())
Configure
WHOOSH_BASE = 'whoosh_index' WHOOSH_ENABLE = True
项目地址:https://github.com/honmaple/flask-msearch