Индекс JSON в SQLAlchemy по Postgresql - PullRequest
1 голос
/ 04 февраля 2020

Я использую JSON в моей модели БД SQLAlchemy:

from sqlalchemy.dialects.postgresql import JSON

class Customer(db.Model):
  id = db.Column(db.Integer, primary_key=True, autoincrement=True)
  custcontext_json = db.Column(JSON, default=lambda: {})

Теперь у меня слишком медленный запрос:

customers = Customer.query.filter(
  Customer.clientid == clientid,
  or_(
    func.lower(Customer.custcontext_json['cinfo', 'userName'].astext.cast(Unicode)).contains(searchterm.lower()),
    func.lower(Customer.custcontext_json['cinfo', 'home', 'sign'].astext.cast(Unicode)).contains(searchterm.lower())
  ),

  or_(
    Customer.custcontext_json['cinfo', 'home', 'status'].astext == 'pre',
    Customer.custcontext_json['cinfo', 'home', 'status'].astext == 'during',
    Customer.custcontext_json['cinfo', 'lastChange'].astext.cast(DateTime) > pendulum.now('UTC').subtract(days=14)
  )
  ).all()

Возможно ли индексировать таблица для этого запроса. Или хотя бы его части?

1 Ответ

0 голосов
/ 15 февраля 2020

Я бы использовал JSONB в качестве формата с более высокой плотностью. Но это не ответ.

Пожалуйста, посмотрите здесь . Операторы для JSON введите PostgreSQL, вы можете получить от здесь . Я хотел бы получить вашу таблицу создания, чтобы воспроизвести что-то на моей стороне. Тем не мение. Я бы начал с чего-то вроде этого:

create table customer (clientid serial, custcontext_json jsonb);

create index on customer (
  (CAST((custcontext_json->'cinfo'->'userName') AS TEXT)),
  (CAST((custcontext_json->'cinfo'->'home'->'sign') AS TEXT)),
  (CAST((custcontext_json->'cinfo'->'home'->'status') AS TEXT)));
...