实现原理

  • 使用sqlalchemy构建原始面向对象的数据模型
  • 支持sqlalchemy的所有主流数据库都可以应用这个技术
  • 在sqlalchemy commit时,使用Naja中的indexservice将模型中的字段索引
  • Naja将搜索方法反注入数据模型

导入库

In [1]:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer, Text, DateTime
from sqlalchemy.engine import create_engine
from sqlalchemy.orm.session import sessionmaker
import naja

初始化数据库

In [2]:
engine = create_engine('sqlite:///:memory:')
# engine = create_engine('sqlite:///test.db/')
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()

定义数据模型

In [3]:
class BlogPost(Base):
    __tablename__ = 'blogpost'
    __searchable__ = ['title', 'content']  # 这些字段将被索引

    id = Column(Integer, primary_key=True)
    title = Column(Text)
    content = Column(Text)

    def __repr__(self):
         return '{0}(title={1})'.format(self.__class__.__name__, self.title)

Base.metadata.create_all(engine)

配置Naja

In [4]:
config = {"WHOOSH_BASE": "/tmp/whoosh"}#索引存储的位置
index_service = naja.IndexService(config=config, session=session)
index_service.register_class(BlogPost)
Out[4]:
FileIndex(FileStorage('/tmp/whoosh/BlogPost'), 'MAIN')

增加数据

In [5]:
m = BlogPost(title=u'第一篇文章的title', content=u'这是第一篇文章的content.')
In [6]:
session.add(m); session.commit()
Building prefix dict from the default dictionary ...
Loading model from cache /var/folders/7s/wk98z9d51p1b9_40kcp0d3c00000gp/T/jieba.cache
Loading model cost 1.068 seconds.
Prefix dict has been built succesfully.
In [7]:
m = BlogPost(title=u'第二篇文章的title', content=u'这是第二篇文章的content.关于naja中indexservice的介绍')
In [8]:
session.add(m); session.commit()

查询

In [9]:
list(BlogPost.search_query(u'文章'))
Out[9]:
[BlogPost(title=第一篇文章的title), BlogPost(title=第二篇文章的title)]
In [10]:
list(BlogPost.search_query(u'title').filter(BlogPost.content.contains('介绍')))
Out[10]:
[BlogPost(title=第二篇文章的title)]
In [11]:
list(BlogPost.search_query(u'naja').filter(BlogPost.id >= 1))
Out[11]:
[BlogPost(title=第二篇文章的title)]
Using with Flask Setup you Flask app, create the db object (db = SQLAlchemy(app)), import your models. Set WHOOSH_BASE to your Whoosh index directory in your Flask , then create the index service and register your models: >>> index_service = IndexService(config=app.config) >>> index_service.register_class(MyFirstModel) >>> index_service.register_class(MySecondModel)