我一直在寻找一种在sqlalchemy中使用tsvector的方法(就像其他方法一样,比如整数,等等),但到目前为止,我还不清楚该怎么做。我读到过可以使用UserDefinedType将tsvector实现为一个类型。经过几次尝试,我一无所获,有人有一个简单的方法来做到这一点吗?谢谢
发布于 2012-12-14 20:45:17
如果您希望SQLAlchemy能够创建具有tsvector类型的模式,并且只在查询中检索序列化的值,那么您需要的是:
from sqlalchemy import types
class tsvector(types.TypeDecorator):
impl = types.UnicodeText
@compiles(tsvector, 'postgresql')
def compile_tsvector(element, compiler, **kw):
return 'tsvector'tsvector的工作方式类似于常规类型,您可以在表定义中使用它。(我忘了在哪里找到了这个代码片段,可能是在SQLAlchemy邮件列表或wiki上。)
如果你真的需要解析tsvector数据,那就有点复杂了。最新版本的hstore支持可能是一个很好的例子。但是,您可能会发现以下代码片段也很有用。这是已知可以工作的旧代码,并且是用pyparsing编写的:
from pyparsing import ParserElement, QuotedString, Regex, Group, Suppress, Group, delimitedList, ZeroOrMore, StringEnd
ParserElement.enablePackrat()
lexeme = QuotedString("'")
occurrence_marker = Regex('[1-9][0-9]*[A-D]?')
atom = Group(lexeme('lexeme') + Suppress(':') + Group(delimitedList(occurrence_marker))('markers'))('atom')
tsvector = ZeroOrMore(atom) + StringEnd()
parse_tsvector = tsvector.parseString更新:
要查询tsvector列,请使用.op()方法,如下所示:
session.query(Model).filter(Model.tsvector.op('@@')(func.plainto_tsquery('search string')))https://stackoverflow.com/questions/13837111
复制相似问题