1/*-------------------------------------------------------------------------
4 * Selectivity estimation functions for text search operators.
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
10 * src/backend/tsearch/ts_selfuncs.c
12 *-------------------------------------------------------------------------
22#include "utils/fmgrprotos.h"
28 * The default text search selectivity is chosen to be small enough to
29 * encourage indexscans for typical table densities. See selfuncs.h and
30 * DEFAULT_EQ_SEL for details.
32 #define DEFAULT_TS_MATCH_SEL 0.005
34/* lookup table type for binary searching through MCELEMs */
41/* type of keys for bsearch'ing through an array of TextFreqs */
50 Datum *mcelem,
int nmcelem,
51 float4 *numbers,
int nnumbers);
56 #define tsquery_opr_selec_no_stats(query) \
57 tsquery_opr_selec(GETQUERY(query), GETOPERAND(query), NULL, 0, 0)
61 * tsmatchsel -- Selectivity of "@@"
63 * restriction selectivity function for tsvector @@ tsquery and
82 * If expression is not variable = something or something = variable, then
83 * punt and return a default estimate.
86 &vardata, &other, &varonleft))
90 * Can't do anything useful if the something is not a constant, either.
99 * The "@@" operator is strict, so we can cope with NULL right away
101 if (((
Const *) other)->constisnull)
108 * OK, there's a Var and a Const we're dealing with here. We need the
109 * Const to be a TSQuery, else we can't do anything useful. We have to
110 * check this because the Var might be the TSQuery not the TSVector.
112 if (((
Const *) other)->consttype == TSQUERYOID)
114 /* tsvector @@ tsquery or the other way around */
121 /* If we can't see the query structure, must punt */
134 * tsmatchjoinsel -- join selectivity of "@@"
136 * join selectivity function for tsvector @@ tsquery and tsquery @@ tsvector
141 /* for the moment we just punt */
147 * @@ selectivity for tsvector var vs tsquery constant
155 /* The caller made sure the const is a TSQuery, so get it now */
158 /* Empty query matches nothing */
159 if (query->
size == 0)
169 /* MCELEM will be an array of TEXT elements for a tsvector column */
175 * There is a most-common-elements slot for the tsvector Var, so
184 /* No most-common-elements info, so do without */
189 * MCE stats count only non-null rows, so adjust for null rows.
191 selec *= (1.0 - stats->stanullfrac);
195 /* No stats at all, so do without */
197 /* we assume no nulls here, so no stanullfrac correction */
204 * Extract data from the pg_statistic arrays into useful format.
208 float4 *numbers,
int nnumbers)
216 * There should be two more Numbers than Values, because the last two
217 * cells are taken for minimal and maximal frequency. Punt if not.
219 * (Note: the MCELEM statistics slot definition allows for a third extra
220 * number containing the frequency of nulls, but we're not expecting that
221 * to appear for a tsvector column.)
223 if (nnumbers != nmcelem + 2)
227 * Transpose the data into a single array so we can use bsearch().
230 for (
i = 0;
i < nmcelem;
i++)
233 * The text Datums came from an array, so it cannot be compressed or
234 * stored out-of-line -- it's safe to use VARSIZE_ANY*.
242 * Grab the lowest MCE frequency. compute_tsvector_stats() stored it for
243 * us in the one before the last cell of the Numbers array.
245 minfreq = numbers[nnumbers - 2];
256 * Traverse the tsquery in preorder, calculating selectivity as:
258 * selec(left_oper) * selec(right_oper) in AND & PHRASE nodes,
260 * selec(left_oper) + selec(right_oper) -
261 * selec(left_oper) * selec(right_oper) in OR nodes,
263 * 1 - select(oper) in NOT nodes
265 * histogram-based estimation in prefix VAL nodes
267 * freq[val] in exact VAL nodes, if the value is in MCELEM
268 * min(freq[MCELEM]) / 2 in VAL nodes, if it is not
270 * The MCELEM array is already sorted (see ts_typanalyze.c), so we can use
271 * binary search for determining freq[MCELEM].
273 * If we don't have stats for the tsvector, we still use this logic,
274 * except we use default estimates for VAL nodes. This case is signaled
283 /* since this function recurses, it could be driven to stack overflow */
292 * Prepare the key for bsearch().
294 key.lexeme = operand +
oper->distance;
299 /* Prefix match, ie the query item is lexeme:* */
306 * Our strategy is to scan through the MCELEM list and combine the
307 * frequencies of the ones that match the prefix. We then
308 * extrapolate the fraction of matching MCELEMs to the remaining
309 * rows, assuming that the MCELEMs are representative of the whole
310 * lexeme population in this respect. (Compare
311 * histogram_selectivity().) Note that these are most common
312 * elements not most common values, so they're not mutually
313 * exclusive. We treat occurrences as independent events.
315 * This is only a good plan if we have a pretty fair number of
316 * MCELEMs available; we set the threshold at 100. If no stats or
317 * insufficient stats, arbitrarily use DEFAULT_TS_MATCH_SEL*4.
319 if (
lookup == NULL || length < 100)
322 matched = allmces = 0;
324 for (
i = 0;
i < length;
i++)
329 if (tlen >=
key.length &&
339 /* Clamp to ensure sanity in the face of roundoff error */
343 selec = matched + (1.0 - allmces) * ((
double) n_matched / length);
346 * In any case, never believe that a prefix match has selectivity
347 * less than we would assign for a non-MCELEM lexeme. This
348 * preserves the property that "word:*" should be estimated to
349 * match at least as many rows as "word" would be.
355 /* Regular exact lexeme match */
358 /* If no stats for the variable, use DEFAULT_TS_MATCH_SEL */
369 * The element is in MCELEM. Return precise selectivity (or
370 * at least as precise as ANALYZE could find out).
377 * The element is not in MCELEM. Estimate its frequency as
378 * half that of the least-frequent MCE. (We know it cannot be
379 * more than minfreq, and it could be a great deal less. Half
380 * seems like a good compromise.) For probably-historical
381 * reasons, clamp to not more than DEFAULT_TS_MATCH_SEL.
389 /* Current TSQuery node is an operator */
419 selec = 0;
/* keep compiler quiet */
424 /* Clamp intermediate results to stay sane despite roundoff error */
431 * bsearch() comparator for a lexeme (non-NULL terminated string with length)
432 * and a TextFreq. Use length, then byte-for-byte comparison, because that's
433 * how ANALYZE code sorted data before storing it in a statistic tuple.
434 * See ts_typanalyze.c for details.
447 /* Compare lengths first, possibly avoiding a strncmp call */
450 else if (len1 < len2)
453 /* Fall back on byte-for-byte comparison */
#define PG_RETURN_FLOAT8(x)
#define PG_GETARG_POINTER(n)
#define PG_GETARG_INT32(n)
Assert(PointerIsAligned(start, uint64))
#define HeapTupleIsValid(tuple)
static void * GETSTRUCT(const HeapTupleData *tuple)
void free_attstatsslot(AttStatsSlot *sslot)
bool get_attstatsslot(AttStatsSlot *sslot, HeapTuple statstuple, int reqkind, Oid reqop, int flags)
#define ATTSTATSSLOT_NUMBERS
#define ATTSTATSSLOT_VALUES
void pfree(void *pointer)
#define IsA(nodeptr, _type_)
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
FormData_pg_statistic * Form_pg_statistic
static Pointer DatumGetPointer(Datum X)
bool get_restriction_variable(PlannerInfo *root, List *args, int varRelid, VariableStatData *vardata, Node **other, bool *varonleft)
#define ReleaseVariableStats(vardata)
#define CLAMP_PROBABILITY(p)
void check_stack_depth(void)
#define tsquery_opr_selec_no_stats(query)
#define DEFAULT_TS_MATCH_SEL
Datum tsmatchjoinsel(PG_FUNCTION_ARGS)
static Selectivity tsquery_opr_selec(QueryItem *item, char *operand, TextFreq *lookup, int length, float4 minfreq)
static Selectivity tsquerysel(VariableStatData *vardata, Datum constval)
Datum tsmatchsel(PG_FUNCTION_ARGS)
static int compare_lexeme_textfreq(const void *e1, const void *e2)
static Selectivity mcelem_tsquery_selec(TSQuery query, Datum *mcelem, int nmcelem, float4 *numbers, int nnumbers)
static TSQuery DatumGetTSQuery(Datum X)
static Size VARSIZE_ANY_EXHDR(const void *PTR)
static bool VARATT_IS_EXTERNAL(const void *PTR)
static char * VARDATA_ANY(const void *PTR)
static bool VARATT_IS_COMPRESSED(const void *PTR)