sqlalchemy的whoosh扩展
WhooshAlchem的Python项目详细描述
支持SqLalChany模型字段的简单文本索引。
BSD许可证。
作者Stefane Fermigier(http://www.fermigier.com/)基于 卡尔·吉尔斯特罗姆的烧瓶炼金术。
快速入门示例
导入此库:
>>> from whooshalchemy import IndexService
标准sqlalchemy导入:
>>> 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
设置sqlalchemy:
>>> engine = create_engine('sqlite:///:memory:') >>> Session = sessionmaker(bind=engine) >>> session = Session() >>> Base = declarative_base()
我们的型号:
>>> class BlogPost(Base): ... __tablename__ = 'blogpost' ... __searchable__ = ['title', 'content'] # these fields will be indexed by whoosh ... ... 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)
创建和初始化索引服务:
>>> config = {"WHOOSH_BASE": "/tmp/whoosh"} >>> index_service = IndexService(config=config, session=session) >>> index_service.register_class(BlogPost) FileIndex(FileStorage('/tmp/whoosh/BlogPost'), 'MAIN')
创建博客文章:
>>> m = BlogPost(title=u'My cool title', content=u'This is the first post.') >>> session.add(m); session.commit()
执行一些搜索:
>>> list(BlogPost.search_query(u'cool')) [BlogPost(title=My cool title)] >>> list(BlogPost.search_query(u'first')) [BlogPost(title=My cool title)]
注意:响应是一个BaseQuery对象,因此可以附加其他sql操作:
>>> list(BlogPost.search_query(u'first').filter(BlogPost.id >= 0)) [BlogPost(title=My cool title)]
与烧瓶一起使用
设置烧瓶应用程序,创建db对象(db = SQLAlchemy(app)),导入模型。
将WHOOSH_BASE设置为烧瓶中的whoosh索引目录,然后创建索引服务 并注册您的型号:
>>> index_service = IndexService(config=app.config) >>> index_service.register_class(MyFirstModel) >>> index_service.register_class(MySecondModel)
等
更改
版本0.3.0(2017/01/09)
- python 3兼容性。
- 使用pytest而不是nose进行测试