2008-12-17

Getting words from tsvector

Sometimes it's needed to get indexed words from tsvector. ts_stat() is good, but not convenvient. Function below allows to use ts_stat with tsvector:

CREATE OR REPLACE FUNCTION ts_stat(tsvector, OUT word text, OUT ndoc
integer, OUT nentry integer)
RETURNS SETOF record AS
$$
    SELECT ts_stat('SELECT ' || quote_literal( $1::text ) || '::tsvector');
$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT IMMUTABLE;

Then, you can use it

select id, (ts_stat(fts)).* from apod where id=1;
 id |    word    | ndoc | nentry
----+------------+------+--------
  1 | 1          |    1 |      1
  1 | 2          |    1 |      2
  1 | io         |    1 |      2
  1 | may        |    1 |      1
  1 | new        |    1 |      1
  1 | red        |    1 |      1
  1 | two        |    1 |      1
  1 | 1979       |    1 |      2
  1 | 1996       |    1 |      1
  1 | 27th       |    1 |      1
  1 | also       |    1 |      1