• Stars
    star
    207
  • Rank 189,769 (Top 4 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created over 7 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Full text search for flask.

flask-msearch

https://img.shields.io/badge/pypi-v0.2.9.2-brightgreen.svg https://img.shields.io/badge/python-2/3-brightgreen.svg https://img.shields.io/badge/license-BSD-blue.svg

Installation

To install flask-msearch:

pip install flask-msearch
# when MSEARCH_BACKEND = "whoosh"
pip install whoosh blinker
# when MSEARCH_BACKEND = "elasticsearch", only for 6.x.x
pip install elasticsearch==6.3.1

Or alternatively, you can download the repository and install manually by doing:

git clone https://github.com/honmaple/flask-msearch
cd flask-msearch
python setup.py install

Quickstart

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 = Post.query.msearch(keyword,fields=['title'],limit=20).filter(...)
    # or
    results = Post.query.filter(...).msearch(keyword,fields=['title'],limit=20).filter(...)
    # elasticsearch
    keyword = "title:book AND content:read"
    # more syntax please visit https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html
    results = Post.query.msearch(keyword,limit=20).filter(...)
    return ''

Config

# when backend is elasticsearch, MSEARCH_INDEX_NAME is unused
# flask-msearch will use table name as elasticsearch index name unless set __msearch_index__
MSEARCH_INDEX_NAME = 'msearch'
# simple,whoosh,elaticsearch, default is simple
MSEARCH_BACKEND = 'whoosh'
# table's primary key if you don't like to use id, or set __msearch_primary_key__ for special model
MSEARCH_PRIMARY_KEY = 'id'
# auto create or update index
MSEARCH_ENABLE = True
# logger level, default is logging.WARNING
MSEARCH_LOGGER = logging.DEBUG
# SQLALCHEMY_TRACK_MODIFICATIONS must be set to True when msearch auto index is enabled
SQLALCHEMY_TRACK_MODIFICATIONS = True
# when backend is elasticsearch
ELASTICSEARCH = {"hosts": ["127.0.0.1:9200"]}

Usage

from flask_msearch import Search
[...]
search = Search()
search.init_app(app)

class Post(db.Model):
    __tablename__ = 'basic_posts'
    __searchable__ = ['title', 'content']

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(49))
    content = db.Column(db.Text)

    def __repr__(self):
        return '<Post:{}>'.format(self.title)

if raise sqlalchemy ValueError,please pass db param to Search

db = SQLalchemy()
search = Search(db=db)

Create_index

search.create_index()
search.create_index(Post)

Update_index

search.update_index()
search.update_index(Post)
# or
search.create_index(update=True)
search.create_index(Post, update=True)

Delete_index

search.delete_index()
search.delete_index(Post)
# or
search.create_index(delete=True)
search.create_index(Post, delete=True)

Custom Analyzer

only for whoosh backend

from jieba.analyse import ChineseAnalyzer
search = Search(analyzer=ChineseAnalyzer())

or use __msearch_analyzer__ for special model

class Post(db.Model):
    __tablename__ = 'post'
    __searchable__ = ['title', 'content', 'tag.name']
    __msearch_analyzer__ = ChineseAnalyzer()

Custom index name

If you want to set special index name for some model.

class Post(db.Model):
    __tablename__ = 'post'
    __searchable__ = ['title', 'content', 'tag.name']
    __msearch_index__ = "post111"

Custom schema

from whoosh.fields import ID

class Post(db.Model):
    __tablename__ = 'post'
    __searchable__ = ['title', 'content', 'tag.name']
    __msearch_schema__ = {'title': ID(stored=True, unique=True), 'content': 'text'}

Note: if you use hybrid_property, default field type is Text unless set special __msearch_schema__

Custom parser

from whoosh.qparser import MultifieldParser

class Post(db.Model):
    __tablename__ = 'post'
    __searchable__ = ['title', 'content']

    def _parser(fieldnames, schema, group, **kwargs):
        return MultifieldParser(fieldnames, schema, group=group, **kwargs)

    __msearch_parser__ = _parser

Note: Only for MSEARCH_BACKEND is whoosh

Custom index signal

flask-msearch uses flask signal to update index by default, if you want to use other asynchronous tools such as celey to update index, please set special MSEARCH_INDEX_SIGNAL

# app.py
app.config["MSEARCH_INDEX_SIGNAL"] = celery_signal
# or use string as variable
app.config["MSEARCH_INDEX_SIGNAL"] = "modulename.tasks.celery_signal"
search = Search(app)

# tasks.py
from flask_msearch.signal import default_signal

@celery.task(bind=True)
def celery_signal_task(self, backend, sender, changes):
    default_signal(backend, sender, changes)
    return str(self.request.id)

def celery_signal(backend, sender, changes):
    return celery_signal_task.delay(backend, sender, changes)

Relate index(Experimental)

for example

class Tag(db.Model):
    __tablename__ = 'tag'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(49))

class Post(db.Model):
    __tablename__ = 'post'
    __searchable__ = ['title', 'content', 'tag.name']

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(49))
    content = db.Column(db.Text)

    # one to one
    tag_id = db.Column(db.Integer, db.ForeignKey('tag.id'))
    tag = db.relationship(
        Tag, backref=db.backref(
            'post', uselist=False), uselist=False)

    def __repr__(self):
        return '<Post:{}>'.format(self.title)

You must add msearch_FUN to Tag model,or the tag.name can’t auto update.

class Tag....
  ......
  def msearch_post_tag(self, delete=False):
      from sqlalchemy import text
      sql = text('select id from post where tag_id=' + str(self.id))
      return {
          'attrs': [{
              'id': str(i[0]),
              'tag.name': self.name
          } for i in db.engine.execute(sql)],
          '_index': Post
      }

More Repositories

1

maple-bbs

a forums system based on flask
Python
468
star
2

maple-blog

a blog website based on flask
Python
117
star
3

emacs-maple-minibuffer

Show minibuffer with another frame
Emacs Lisp
75
star
4

maple-file

upload and storage images server in python.
Python
39
star
5

maple-poetry

古诗词接口 By Go
Go
27
star
6

emacs-maple-preview

markdown, org-mode or html realtime preview on Emacs
JavaScript
24
star
7

emacs-maple-explorer

Create file, imenu, buffer sidebar on Emacs quickly
Emacs Lisp
20
star
8

org-python

convert orgmode to html based on python.
Python
16
star
9

maple-json

sqlalchemy serializer to json
Python
9
star
10

flask-avatar

To generate avatar for flask
Python
8
star
11

emacs-maple-scratch

Show recent files and projects in scratch buffer.
Emacs Lisp
7
star
12

forest

lightweight and fast HTTP router written in Go
Go
7
star
13

maple-emacs

Emacs configuration
Emacs Lisp
6
star
14

emacs-maple-tabbar

show tabbar in emacs
Emacs Lisp
6
star
15

flask-maple

flask tips
Python
6
star
16

emacs-maple-imenu

imenu
Emacs Lisp
5
star
17

emacs-maple-modeline

Beautiful emacs modeline
Emacs Lisp
5
star
18

emacs-maple-translate

Translate word between chinese and english.
Emacs Lisp
4
star
19

snow

static site generator
Go
4
star
20

dotfiles

My linux config about i3,vim,emacs,conky.....
CSS
4
star
21

emacs-maple-echoarea

Auto hide echo area and show modeline
Emacs Lisp
4
star
22

emacs-maple-run

Execute buffer code with comint mode.
Emacs Lisp
3
star
23

emacs-maple-package

Speed up emacs startup.
Emacs Lisp
3
star
24

emacs-maple-iedit

Emacs multiple cursors support based on iedit.
Emacs Lisp
3
star
25

emacs-maple-line

emacs hide mode line of every buffer but with single maple line
Emacs Lisp
3
star
26

honmaple.github.io

my blog based on pelican
HTML
2
star
27

emacs-maple-env

Isolate emacs dependency environment
Emacs Lisp
2
star
28

meting-api

MetingJS服务端的Golang实现
Go
2
star
29

maple-scheduler

scheduler
Python
2
star
30

orgmode_reader

pelican org-mode reader
Python
1
star
31

org-golang

Convert org-mode to html by golang
Go
1
star
32

emacs-maple-note

Emacs Lisp
1
star
33

fortune

fortune with python
Python
1
star
34

emacs-maple-xpm

Beautiful string separators by xpm image.
Emacs Lisp
1
star