这是为
JSONB创建索引的当前代码.
Index("mytable_data_idx_id_key",Mytable.data['id'].astext,postgresql_using='gin')
但我得到了这个错误.
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) data type text has no default operator class for access method "gin" HINT: You must specify an operator class for the index or define a default operator class for the data type. [sql: "CREATE INDEX event_data_idx_id_key ON event USING gin ((data ->> 'id'))"]
有没有办法在sqlAlchemy上创建索引?
Postgresql特定的sqlAlchemy文档在
http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#operator-classes提到了postgresql_ops字典,以提供Postgresql使用的“运算符类”,并提供此示例说明其用法:
原文链接:https://www.f2er.com/postgresql/191907.htmlIndex('my_index',my_table.c.id,my_table.c.data,postgresql_ops={ 'data': 'text_pattern_ops','id': 'int4_ops' })
从实验开始,如果要为表达式索引指定“运算符类”,则似乎需要使用text()索引描述.所以,
db.Index( 'ix_sample',sqlalchemy.text("(jsoncol->'values') jsonb_path_ops"),postgresql_using="gin")
…在__table_args__中,对于ORM模型,在包含字符串数组的jsonb字段上指定GIN索引,并允许有效查找,即匹配JSON数组字段中的任何字符串,如下所示:
{ "values": ["first","second","third"],"other": "fields","go": "here" }
import sqlalchemy from sqlalchemy.dialects import postgresql query = session.query(MyModel).filter( sqlalchemy.type_coerce(MyModel.jsoncol['values'],postgresql.JSONB) .contains(sqlalchemy.type_coerce("second",postgresql.JSONB))) results = query.all()