如何在SQLAlchemy上使用GIN创建jsonb索引?
发布时间:2020-12-13 16:14:07 所属栏目:百科 来源:网络整理
导读:这是为 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
这是为
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使用的“运算符类”,并提供此示例说明其用法:
Index('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" } 使用@>查询PostgreSQL中的运算符看起来像这样: 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() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |