Skip to content

Instantly share code, notes, and snippets.

@glittershark
Created August 20, 2013 19:42
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save glittershark/6286217 to your computer and use it in GitHub Desktop.
Save glittershark/6286217 to your computer and use it in GitHub Desktop.
Postgresql aggregate function for tsvectors
CREATE OR REPLACE FUNCTION concat_tsvectors(tsv1 tsvector, tsv2 tsvector)
RETURNS tsvector AS $$
BEGIN
RETURN coalesce(tsv1, to_tsvector('default', ''))
|| coalesce(tsv2, to_tsvector('default', ''));
END;
$$ LANGUAGE plpgsql;
CREATE AGGREGATE tsvector_agg (
BASETYPE = tsvector,
SFUNC = concat_tsvectors,
STYPE = tsvector,
INITCOND = ''
);
@EvanCarroll
Copy link

EvanCarroll commented Apr 12, 2017

There is a tsvector_concat, and has been one since 8.3 https://www.postgresql.org/docs/8.3/static/functions-textsearch.html Why create another one?

@shanginn
Copy link

@EvanCarroll, can you write an example with tsvector_concat? Or provide more info, I can't find any info regarding this function.

@reedstrm
Copy link

reedstrm commented Oct 4, 2017

It's the implementation behind the || operator (concatenate) for tsvector:

postgres=# select op.* from pg_operator op join pg_type t on oprleft = t.oid where oprname = '||' and typname = 'tsvector';
-[ RECORD 1 ]+----------------
oprname      | ||
oprnamespace | 11
oprowner     | 10
oprkind      | b
oprcanmerge  | f
oprcanhash   | f
oprleft      | 3614
oprright     | 3614
oprresult    | 3614
oprcom       | 0
oprnegate    | 0
oprcode      | tsvector_concat
oprrest      | -
oprjoin      | -

postgres=# \df tsvector_concat
List of functions
-[ RECORD 1 ]-------+-------------------
Schema              | pg_catalog
Name                | tsvector_concat
Result data type    | tsvector
Argument data types | tsvector, tsvector
Type                | normal

You can drop it in for the sfunc in your aggregate def above.

@Jl14Salvador
Copy link

Jl14Salvador commented Mar 1, 2019

@EvanCarroll Although I see that tsvector_concat is available by using the command \df+ tsvector_concat, I can't find any single point of documentation that shows that this function exists in the Postgres Docs. Regardless, thanks for the info!

@molomby
Copy link

molomby commented Oct 1, 2019

A version using the built in tsvector_concat function as suggested by @EvanCarroll:

create aggregate tsvector_agg (tsvector) (
	STYPE = pg_catalog.tsvector,
	SFUNC = pg_catalog.tsvector_concat,
	INITCOND = ''
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment