Sqlalchemy extension for dealing with sphinxql
sqlalchemy_sphinx的Python项目详细描述
SqlAlchemy Sphinx是SqlAlchemy的方言,它转换SqlAlchemy 将模型转换为兼容的SQL for Sphinx。
这种方言适用于python 2和3。当前需要导入 sqlalchemy_sphinx以正确注册python 3。
安装
sqlalchemy sphinx在pypi上的包名下可用 sqlalchemy-sphinx,您可以通过运行获得:
pip install sqlalchemy-sphinx
用法
定义sphinx sqlalchemy与创建 sqlalchemy模型。
fromsqlalchemyimportcreate_engine,Column,Integer,String,BigInteger,Unicode,Enumfromsqlalchemy.ext.declarativeimportdeclarative_basefromsqlalchemy.ormimportdeferred,sessionmakersphinx_engine=create_engine('sphinx://your.sphinx.host:9008')SphinxBase=declarative_base(bind=sphinx_engine)SphinxSession=sessionmaker(bind=sphinx_engine)sphinx_session=SphinxSession()classMockSphinxModel(Base):__tablename__="mock_table"name=Column(String)id=Column(Integer,primary_key=True)country=Column(String)ranker=deferred(Column(String))group_by_dummy=deferred(Column(String))max_matches=deferred(Column(String))field_weights=deferred(Column(String))
创建模型后,我们可以对模型运行查询:
query=session.query(MockSphinxModel).limit(100)# 'SELECT name, id, country FROM mock_table LIMIT 0, 100'
我们还可以进行匹配
base_query=session.query(MockSphinxModel.id)query=base_query.filter(MockSphinxModel.country.match("US"))# "SELECT id FROM mock_table WHERE MATCH('(@country US)')"query=base_query.filter(MockSphinxModel.name.match("adriel"),MockSphinxModel.country.match("US"))# "SELECT id FROM mock_table WHERE MATCH('(@name adriel) (@country US)')"
选项:
query=session.query(MockSphinxModel.id)query=query.filter(func.options(MockSphinxModel.field_weights==["title=10","body=3"]))# 'SELECT id FROM mock_table OPTION field_weights=(title=10, body=3)'query=session.query(MockSphinxModel.id)query=query.filter(MockSphinxModel.country.match("US"),func.options(MockSphinxModel.max_matches==1))# "SELECT id FROM mock_table WHERE MATCH('(@country US)') OPTION max_matches=1"