Мне нужно искать с помощью одного поля, который называется именем , который может соответствовать либо первой, либо последней_name. Ilike оператор я не могу использовать.
Матч должен быть нечувствительным, поэтому запрос
Код: Выделить всё
SELECT *
FROM people AS p
WHERE
LOWER(p.last_name || p.first_name) LIKE :name
OR
LOWER(p.first_name || p.last_name) LIKE :name
Моя модель
Код: Выделить всё
import sqlalchemy as sa
from sqlalchemy.orm import Mapped, mapped_column
class People(DeclarativeBase):
__tablename__ = "people"
id: Mapped[str] = mapped_column(primary_key=True)
first_name: Mapped[str] = mapped_column(nullable=False, unique=False)
last_name: Mapped[str] = mapped_column(nullable=False, unique=False)
__table_args__ = (
sa.Index(
"ix_people_last_first_name",
sa.text("LOWER(last_name || first_name)"),
),
sa.Index(
"ix_people_first_last_name",
sa.text("LOWER(first_name || last_name)"),
),
)
< /code>
Когда я генерирую миграцию с алембиком, я получаю < /p>
INFO [alembic.autogenerate.compare] Detected added table 'people'
INFO [alembic.autogenerate.compare] Detected added index ''ix_people_first_last_name'' on '()'
INFO [alembic.autogenerate.compare] Detected added index ''ix_people_last_first_name'' on '()'
< /code>
Как видите, индексы не применяются к столбцу (ы).
они создаются, хотя: < /p>
op.create_index('ix_people_first_last_name', 'people', [sa.literal_column('LOWER(first_name || last_name)')], unique=False)
op.create_index('ix_people_last_first_name', 'people', [sa.literal_column('LOWER(last_name || first_name)')], unique=False)
< /code>
EXPLAIN
Код: Выделить всё
"Seq Scan on people p (cost=0.00..4.50 rows=3 width=128)"
" Filter: ((lower(((last_name)::text || (first_name)::text)) ~~ 'fra%'::text) OR (lower(((first_name)::text || (last_name)::text)) ~~ 'fra%'::text))"
< /code>
which shows the indexes are not used.
SQLAlchemy says here it is possible to use lower
Код: Выделить всё
the text() construct may be used to specify Index expressions, provided the Index is explicitly associated with the Table.
Как я могу его достичь? /> Большое спасибо < /p>
Подробнее здесь: https://stackoverflow.com/questions/796 ... with-lower