python - 如何在 SQLAlchemy 上使用 GIN 创建 jsonb 索引?

标签 python postgresql indexing sqlalchemy

这是为 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")

...in __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()

关于python - 如何在 SQLAlchemy 上使用 GIN 创建 jsonb 索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30885846/

相关文章:

php - 在php中获取包含美元字符的PDO结果集

sql - Postgresql函数,结果集到变量中

postgresql - 在一个语句中从 jsonb 列中删除多个键

sql - MySql,任何人都可以建议如何改进我的查询/索引吗?

C 程序 - 从另一个文件构建索引文件

python - Visual Studio 2017 中缺少 io.h header

python - Sublime Text 语法 : Python 3. 6 个 f 字符串

python - 通过整数索引选择和修改 Pandas 数据框中的切片

python - 深度学习库 Neon DataIterator/ArrayIterator 初始化错误

python - 如何在 Markdown 标题中写入 Python 字符串变量?