Il PostgreSQL docs specifica SQLAlchemy a http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#operator-classes citarne dizionario postgresql_ops
per fornire la "classe gestore" usata da PostgreSQL, e fornire questo esempio che illustra il suo utilizzo:
Index('my_index', my_table.c.id, my_table.c.data,
postgresql_ops={
'data': 'text_pattern_ops',
'id': 'int4_ops'
})
Da sperimentare, sembra che avete bisogno di utilizzare una descrizione dell'indice text()
se si desidera specificare la "classe operatore" per un indice di espressione. Così,
db.Index(
'ix_sample',
sqlalchemy.text("(jsoncol->'values') jsonb_path_ops"),
postgresql_using="gin")
... in __table_args__
per un modello ORM specifica un indice GIN su un campo jsonb
che contiene un array di stringhe, e che consente per le ricerche efficienti, cioè corrispondente su una delle stringhe in JSON campo matrice che assomiglia a questo:
{
"values": ["first", "second", "third"],
"other": "fields",
"go": "here"
}
Interrogazione utilizzando l'operatore @>
in PostgreSQL sarebbe simile a questa:
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()
fonte
2015-08-04 10:53:24
I tRIE ma ho avuto un errore 'sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) classe operatore" text_pattern_ops "non accetta il tipo di dati jsonb' –
ho aggiornato la mia risposta con altri esempi –