Skip to content

Text search values

PgTsVector holds a tsvector, a document’s sorted lexemes with their positions. PgTsQuery holds a tsquery, lexemes combined with &, |, ! and phrase operators. Both carry the bytes PostgreSQL stores, so a value read from a table passes back unchanged, and both default to the empty value.

[PgFunction]
public static float Score(PgTsVector document, string search)
=> document.Rank(PgTsQuery.FromWebSearchText(search));
SELECT score(to_tsvector('english', 'The fat rats ate'), 'fat rat'); -- 0.09910322

Parsing, formatting, matching, ranking and ordering call PostgreSQL’s own text search functions, so they need a backend callback.

Parse reads a value’s text as a cast does, without normalizing words. FromText normalizes a document with to_tsvector, or a query with to_tsquery. PgTsQuery also has FromPlainText, FromPhraseText and FromWebSearchText, which match plainto_tsquery, phraseto_tsquery and websearch_to_tsquery. Each uses the configuration that default_text_search_config names unless you pass a PgTsConfig:

if (PgTsConfig.TryFind("english", out PgTsConfig english))
{
PgTsVector document = PgTsVector.FromText(english, "The fat rats ate the fat cats");
// 'ate':4 'cat':7 'fat':2,6 'rat':3
}

TryFind returns false for a name that names no configuration, including a malformed one. Unlike the regconfig cast, it doesn’t read a string of digits as an OID. Invalid text in Parse or PgTsQuery.FromText throws a PgException with SQLSTATE 42601.

SQL C#
document @@ query document.Matches(query)
a || b for documents a.Concat(b) or a | b
a && b, a || b, !! a for queries a.And(b), a.Or(b), a.Not(), or a & b, a | b, !a
a <-> b, tsquery_phrase(a, b, n) a.FollowedBy(b), a.FollowedBy(b, n)
ts_rank, ts_rank_cd Rank, RankCoverDensity, optionally with PgTsRankWeights and PgTsRankNormalization
length(document) document.Count

GetLexemes reads a document’s lexemes in stored order, each with its positions and PgTsWeight labels, as unnest(tsvector) lists them. GetItems reads a query’s operands and operators in stored prefix order: each operator comes before its right operand, then its left.

CompareTo and the comparison operators order values as PostgreSQL does. A PgTsVector is equal to another when their stored bytes are, which PostgreSQL keeps sorted and unique. A PgTsQuery follows PostgreSQL’s equality, which ignores labels and prefix flags, so 'a:A' equals 'a'; comparing or hashing two queries with different bytes calls PostgreSQL.