Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape underscores in while preparing tsquery for PostgreSQL full text search?

I have below plainto_tsquery query as part of full text searching on a PostgreSQL table.

SELECT plainto_tsquery('english', 'flat discount on flight_tickets');

This query will return 'flat' & 'discount' & 'flight' & 'ticket'

Is there any way to make it to return 'flat' & 'discount' & 'flight_ticket'

Just to avoid closing ticket by marking as duplicate, I have checked below stackoverflow questions

  • Escaping special characters in to_tsquery
  • PSQLException: ERROR: syntax error in tsquery
like image 786
Mithun Sreedharan Avatar asked Sep 12 '25 10:09

Mithun Sreedharan


1 Answers

You could "pre-process" the text and the queries to replace _ with a different character like /.

CREATE INDEX ON texts USING gin (to_tsvector('english', replace(doc, '_', '/')));

SELECT * FROM texts
WHERE to_tsvector('english', replace(doc, '_', '/'))
      @@ plainto_tsquery('english', replace('flat discount on flight_tickets', '_', '/'));
like image 199
Laurenz Albe Avatar answered Sep 15 '25 02:09

Laurenz Albe