2015-06-17 9 views
5

Ecco l'indice di creazione del codice corrente per JSONB.Come creare l'indice jsonb usando GIN su SQLAlchemy?

Index("mytable_data_idx_id_key", Mytable.data['id'].astext, postgresql_using='gin') 

Ma ho ricevuto questo errore.

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'))"] 

C'è un modo per creare indici su SQLAlchemy?

risposta

1

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() 
+0

I tRIE ma ho avuto un errore 'sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) classe operatore" text_pattern_ops "non accetta il tipo di dati jsonb' –

+0

ho aggiornato la mia risposta con altri esempi –

Problemi correlati