I'm trying to optimize these slow queries (excuse the SQL mixed with Ruby on Rails):
WHERE name ILIKE %<the user's search text>%
WHERE lower(NAME) LIKE :search OR lower(BARCODE) LIKE :search OR lower(SKU) like :search, search: "%<the user's search text>%"
As you can see, these are wildcard queries with the %
at the beginning and end, which means normal indexing is useless. The table consists of items, and the queries are fine when there are not a lot of items for the user, but when the user has a lot of items (tens of thousands), this takes a long time (like tens of seconds). How can I improve the performance? The search text is a portion of a barcode or name of the product, so it's different than if I was just trying to search for text (I'd use full text search in that case so that searches for 'dog' would yield results containing 'dogs' or 'doggy', etc.). In one of the use cases, I'm also searching across multiple columns on the same table.
Some initial approaches I considered but not sure if these will work:
- full text search (add a column that is the
to_tsvector
of the multiple columns to search on then add a gin index for the new column) - trigram index (more suitable?)
- other suggestions I've not thought of
I'm using PostgreSQL 13 and Ruby on Rails.