Search code examples
postgresqlfull-text-searchtsvector

Is there a ts (text search) function would return found string instead of boolean?


I am using PostgreSQL to find out the matched string in the article by using tsvector and tsquery.

I read the PostgreSQL manual 12.3 Controlling Text Search but nothing could help me to get the exact output I wanted.

Query:

SELECT ts_headline('english',
  'The most common type of search
is to find all documents containing given query terms
and return them in order of their similarity to the
query.',
  to_tsquery('query & similarity'),
  'StartSel = <, StopSel = >');

ts_headline output

The most common type of search
is to find all documents containing given <query> terms
and return them in order of their <similarity> to the
<query>.    

I'm looking for the only string as mentioned below:

query, similarity


Solution

  • If you pick delimiters for StartSel and StopSel that you are sure do not exist elsewhere in the string, then it is pretty easy to do this with a regexp.

     SELECT  distinct regexp_matches[1] from
         regexp_matches(
            ts_headline('english',
      'The most common type of search
    is to find all documents containing given query terms
    and return them in order of their similarity to the
    query.',
                to_tsquery('query & similarity'),
                'StartSel = <, StopSel = >'
             ),
             '<(.*?)>','g'
         );