PostgreSQL – How to Create a Citation from a Text Field

full-text-searchpostgresql

I have a database with a lot of text and I want to find the surrounding text for a word that I am searching for i.e. If I search this text for "text" I should get something like (and more consistent than):

  • .. lot of text and ..
  • .. the surrounding text for ..
  • .. this text for "text"..
  • .. for "text" I should ..

I can write this in a program but I wondered if there is a good SQL trick to get something approaching this with just a query for a quick and dirty report.

Best Answer

what you need is the ts_headline function. it does exactly what you need it seems. here is the documentation: http://www.postgresql.org/docs/9.4/static/textsearch-controls.html