[英]How to create GIN index on text array column in SQLAlchemy (with PostgreSQL and python)
[英]How to create jsonb index using GIN on 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 上創建索引?
http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#operator-classes 上的 PostgreSQL 特定 SQLAlchemy 文檔提到了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模型指定上的一個索引GIN jsonb
字段包含一個字符串數組,並且,可實現有效的查找,即匹配於任何以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()
我不知道自上一個接受的答案以來 sqlalchemy 中的情況是否發生了變化,但在我工作的代碼庫中,這是通過以下方式完成的:
__table_args__ = (
db.Index(
"index_TABLENAME_on_COLUMN_gin",
"COLUMN",
postgresql_using="gin",
),
)
這將在 Postgresql 中創建預期的 GIN 索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.