-1

How do I index the following statement with an un-anchored search pattern

SELECT somefield
FROM sometable 
WHERE lower(somefield2) like '%foo%';

Some rows have more than 2k bytes.

Evan Carroll
  • 63,051
  • 46
  • 242
  • 479
Ivan Alex
  • 9
  • 2
  • You had a bunch of stuff in the question that was not relevant to what you were looking for, I cropped it out. Sometimes a simple question just needs to be phrased simply, welcome to [dba.se] – Evan Carroll May 05 '18 at 18:56

1 Answers1

5

The length aside, a btree index would not help that query. You could create a hash index but that would also only help if the query wants an exact match for the whole column. not for a substring pattern. To do what you want first, add the pg_trgm extension:

CREATE EXTENSION pg_trgm;

Then create a trigram index:

CREATE INDEX trgm_idx ON sometable
  USING GIN (somefield2 gin_trgm_ops); -- can also be GIST

A trigram index can help find matches for SQL's LIKE and ILIKE and regex patterns.

For more information see the docs on pg_trgm

Evan Carroll
  • 63,051
  • 46
  • 242
  • 479
Jasen
  • 3,563
  • 1
  • 13
  • 17