I went and recorded how long it took before the page timed out. Approximately 22 seconds. Down the rabbithole you go from there.
Generic tip from my experience:
get the SQL query executed by User.search()
run EXPLAIN ANALYZE {SQL QUERY} and see what's going on (you can use tools like explain.depesz.com/ to make it more readable)
check what's the situation with indices
IIRC .search comes from Ransack which likely uses LIKE or ILIKE which can be a very expensive operation (22 seconds is definitely too much) with a non trivial amount of rows to scan. LIKE operators don't use indexes which means the DB has to sequentially scan each row to provide an answer:
The previously accepted answer was incorrect. Full Text Search with its full text indexes is not for the LIKE operator at all, it has its own operators and doesn't work for arbitrary strings. It operates on words based on dictionaries and stemming. It does support…
Generic tip from my experience:
User.search()
EXPLAIN ANALYZE {SQL QUERY}
and see what's going on (you can use tools like explain.depesz.com/ to make it more readable)IIRC
.search
comes from Ransack which likely usesLIKE
orILIKE
which can be a very expensive operation (22 seconds is definitely too much) with a non trivial amount of rows to scan.LIKE
operators don't use indexes which means the DB has to sequentially scan each row to provide an answer:You could use trigrams, with the extension
pg_tgrm
to enable index scanning onLIKE
operators:Note the difference in execution time ;-)
This is a great answer:
answer re: PostgreSQL LIKE query performance variations
FTS does not support
LIKE
The previously accepted answer was incorrect. Full Text Search with its full text indexes is not for the
LIKE
operator at all, it has its own operators and doesn't work for arbitrary strings. It operates on words based on dictionaries and stemming. It does support…and here you can find more details on
pg_tgrm
: postgresql.org/docs/12/pgtrgm.htmlHope this helps :-)
I'm writing on a yellow stickie as a reminder.
I forget EXPLAIN exists time and time again. Thank you!