Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * ts_typanalyze.c
4 : * functions for gathering statistics from tsvector columns
5 : *
6 : * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7 : *
8 : *
9 : * IDENTIFICATION
10 : * src/backend/tsearch/ts_typanalyze.c
11 : *
12 : *-------------------------------------------------------------------------
13 : */
14 : #include "postgres.h"
15 :
16 : #include "access/hash.h"
17 : #include "catalog/pg_operator.h"
18 : #include "commands/vacuum.h"
19 : #include "tsearch/ts_type.h"
20 : #include "utils/builtins.h"
21 :
22 :
23 : /* A hash key for lexemes */
24 : typedef struct
25 : {
26 : char *lexeme; /* lexeme (not NULL terminated!) */
27 : int length; /* its length in bytes */
28 : } LexemeHashKey;
29 :
30 : /* A hash table entry for the Lossy Counting algorithm */
31 : typedef struct
32 : {
33 : LexemeHashKey key; /* This is 'e' from the LC algorithm. */
34 : int frequency; /* This is 'f'. */
35 : int delta; /* And this is 'delta'. */
36 : } TrackItem;
37 :
38 : static void compute_tsvector_stats(VacAttrStats *stats,
39 : AnalyzeAttrFetchFunc fetchfunc,
40 : int samplerows,
41 : double totalrows);
42 : static void prune_lexemes_hashtable(HTAB *lexemes_tab, int b_current);
43 : static uint32 lexeme_hash(const void *key, Size keysize);
44 : static int lexeme_match(const void *key1, const void *key2, Size keysize);
45 : static int lexeme_compare(const void *key1, const void *key2);
46 : static int trackitem_compare_frequencies_desc(const void *e1, const void *e2);
47 : static int trackitem_compare_lexemes(const void *e1, const void *e2);
48 :
49 :
50 : /*
51 : * ts_typanalyze -- a custom typanalyze function for tsvector columns
52 : */
53 : Datum
54 1 : ts_typanalyze(PG_FUNCTION_ARGS)
55 : {
56 1 : VacAttrStats *stats = (VacAttrStats *) PG_GETARG_POINTER(0);
57 1 : Form_pg_attribute attr = stats->attr;
58 :
59 : /* If the attstattarget column is negative, use the default value */
60 : /* NB: it is okay to scribble on stats->attr since it's a copy */
61 1 : if (attr->attstattarget < 0)
62 1 : attr->attstattarget = default_statistics_target;
63 :
64 1 : stats->compute_stats = compute_tsvector_stats;
65 : /* see comment about the choice of minrows in commands/analyze.c */
66 1 : stats->minrows = 300 * attr->attstattarget;
67 :
68 1 : PG_RETURN_BOOL(true);
69 : }
70 :
71 : /*
72 : * compute_tsvector_stats() -- compute statistics for a tsvector column
73 : *
74 : * This functions computes statistics that are useful for determining @@
75 : * operations' selectivity, along with the fraction of non-null rows and
76 : * average width.
77 : *
78 : * Instead of finding the most common values, as we do for most datatypes,
79 : * we're looking for the most common lexemes. This is more useful, because
80 : * there most probably won't be any two rows with the same tsvector and thus
81 : * the notion of a MCV is a bit bogus with this datatype. With a list of the
82 : * most common lexemes we can do a better job at figuring out @@ selectivity.
83 : *
84 : * For the same reasons we assume that tsvector columns are unique when
85 : * determining the number of distinct values.
86 : *
87 : * The algorithm used is Lossy Counting, as proposed in the paper "Approximate
88 : * frequency counts over data streams" by G. S. Manku and R. Motwani, in
89 : * Proceedings of the 28th International Conference on Very Large Data Bases,
90 : * Hong Kong, China, August 2002, section 4.2. The paper is available at
91 : * http://www.vldb.org/conf/2002/S10P03.pdf
92 : *
93 : * The Lossy Counting (aka LC) algorithm goes like this:
94 : * Let s be the threshold frequency for an item (the minimum frequency we
95 : * are interested in) and epsilon the error margin for the frequency. Let D
96 : * be a set of triples (e, f, delta), where e is an element value, f is that
97 : * element's frequency (actually, its current occurrence count) and delta is
98 : * the maximum error in f. We start with D empty and process the elements in
99 : * batches of size w. (The batch size is also known as "bucket size" and is
100 : * equal to 1/epsilon.) Let the current batch number be b_current, starting
101 : * with 1. For each element e we either increment its f count, if it's
102 : * already in D, or insert a new triple into D with values (e, 1, b_current
103 : * - 1). After processing each batch we prune D, by removing from it all
104 : * elements with f + delta <= b_current. After the algorithm finishes we
105 : * suppress all elements from D that do not satisfy f >= (s - epsilon) * N,
106 : * where N is the total number of elements in the input. We emit the
107 : * remaining elements with estimated frequency f/N. The LC paper proves
108 : * that this algorithm finds all elements with true frequency at least s,
109 : * and that no frequency is overestimated or is underestimated by more than
110 : * epsilon. Furthermore, given reasonable assumptions about the input
111 : * distribution, the required table size is no more than about 7 times w.
112 : *
113 : * We set s to be the estimated frequency of the K'th word in a natural
114 : * language's frequency table, where K is the target number of entries in
115 : * the MCELEM array plus an arbitrary constant, meant to reflect the fact
116 : * that the most common words in any language would usually be stopwords
117 : * so we will not actually see them in the input. We assume that the
118 : * distribution of word frequencies (including the stopwords) follows Zipf's
119 : * law with an exponent of 1.
120 : *
121 : * Assuming Zipfian distribution, the frequency of the K'th word is equal
122 : * to 1/(K * H(W)) where H(n) is 1/2 + 1/3 + ... + 1/n and W is the number of
123 : * words in the language. Putting W as one million, we get roughly 0.07/K.
124 : * Assuming top 10 words are stopwords gives s = 0.07/(K + 10). We set
125 : * epsilon = s/10, which gives bucket width w = (K + 10)/0.007 and
126 : * maximum expected hashtable size of about 1000 * (K + 10).
127 : *
128 : * Note: in the above discussion, s, epsilon, and f/N are in terms of a
129 : * lexeme's frequency as a fraction of all lexemes seen in the input.
130 : * However, what we actually want to store in the finished pg_statistic
131 : * entry is each lexeme's frequency as a fraction of all rows that it occurs
132 : * in. Assuming that the input tsvectors are correctly constructed, no
133 : * lexeme occurs more than once per tsvector, so the final count f is a
134 : * correct estimate of the number of input tsvectors it occurs in, and we
135 : * need only change the divisor from N to nonnull_cnt to get the number we
136 : * want.
137 : */
138 : static void
139 1 : compute_tsvector_stats(VacAttrStats *stats,
140 : AnalyzeAttrFetchFunc fetchfunc,
141 : int samplerows,
142 : double totalrows)
143 : {
144 : int num_mcelem;
145 1 : int null_cnt = 0;
146 1 : double total_width = 0;
147 :
148 : /* This is D from the LC algorithm. */
149 : HTAB *lexemes_tab;
150 : HASHCTL hash_ctl;
151 : HASH_SEQ_STATUS scan_status;
152 :
153 : /* This is the current bucket number from the LC algorithm */
154 : int b_current;
155 :
156 : /* This is 'w' from the LC algorithm */
157 : int bucket_width;
158 : int vector_no,
159 : lexeme_no;
160 : LexemeHashKey hash_key;
161 : TrackItem *item;
162 :
163 : /*
164 : * We want statistics_target * 10 lexemes in the MCELEM array. This
165 : * multiplier is pretty arbitrary, but is meant to reflect the fact that
166 : * the number of individual lexeme values tracked in pg_statistic ought to
167 : * be more than the number of values for a simple scalar column.
168 : */
169 1 : num_mcelem = stats->attr->attstattarget * 10;
170 :
171 : /*
172 : * We set bucket width equal to (num_mcelem + 10) / 0.007 as per the
173 : * comment above.
174 : */
175 1 : bucket_width = (num_mcelem + 10) * 1000 / 7;
176 :
177 : /*
178 : * Create the hashtable. It will be in local memory, so we don't need to
179 : * worry about overflowing the initial size. Also we don't need to pay any
180 : * attention to locking and memory management.
181 : */
182 1 : MemSet(&hash_ctl, 0, sizeof(hash_ctl));
183 1 : hash_ctl.keysize = sizeof(LexemeHashKey);
184 1 : hash_ctl.entrysize = sizeof(TrackItem);
185 1 : hash_ctl.hash = lexeme_hash;
186 1 : hash_ctl.match = lexeme_match;
187 1 : hash_ctl.hcxt = CurrentMemoryContext;
188 1 : lexemes_tab = hash_create("Analyzed lexemes table",
189 : num_mcelem,
190 : &hash_ctl,
191 : HASH_ELEM | HASH_FUNCTION | HASH_COMPARE | HASH_CONTEXT);
192 :
193 : /* Initialize counters. */
194 1 : b_current = 1;
195 1 : lexeme_no = 0;
196 :
197 : /* Loop over the tsvectors. */
198 509 : for (vector_no = 0; vector_no < samplerows; vector_no++)
199 : {
200 : Datum value;
201 : bool isnull;
202 : TSVector vector;
203 : WordEntry *curentryptr;
204 : char *lexemesptr;
205 : int j;
206 :
207 508 : vacuum_delay_point();
208 :
209 508 : value = fetchfunc(stats, vector_no, &isnull);
210 :
211 : /*
212 : * Check for null/nonnull.
213 : */
214 508 : if (isnull)
215 : {
216 0 : null_cnt++;
217 0 : continue;
218 : }
219 :
220 : /*
221 : * Add up widths for average-width calculation. Since it's a
222 : * tsvector, we know it's varlena. As in the regular
223 : * compute_minimal_stats function, we use the toasted width for this
224 : * calculation.
225 : */
226 508 : total_width += VARSIZE_ANY(DatumGetPointer(value));
227 :
228 : /*
229 : * Now detoast the tsvector if needed.
230 : */
231 508 : vector = DatumGetTSVector(value);
232 :
233 : /*
234 : * We loop through the lexemes in the tsvector and add them to our
235 : * tracking hashtable.
236 : */
237 508 : lexemesptr = STRPTR(vector);
238 508 : curentryptr = ARRPTR(vector);
239 29325 : for (j = 0; j < vector->size; j++)
240 : {
241 : bool found;
242 :
243 : /*
244 : * Construct a hash key. The key points into the (detoasted)
245 : * tsvector value at this point, but if a new entry is created, we
246 : * make a copy of it. This way we can free the tsvector value
247 : * once we've processed all its lexemes.
248 : */
249 28817 : hash_key.lexeme = lexemesptr + curentryptr->pos;
250 28817 : hash_key.length = curentryptr->len;
251 :
252 : /* Lookup current lexeme in hashtable, adding it if new */
253 28817 : item = (TrackItem *) hash_search(lexemes_tab,
254 : (const void *) &hash_key,
255 : HASH_ENTER, &found);
256 :
257 28817 : if (found)
258 : {
259 : /* The lexeme is already on the tracking list */
260 27676 : item->frequency++;
261 : }
262 : else
263 : {
264 : /* Initialize new tracking list element */
265 1141 : item->frequency = 1;
266 1141 : item->delta = b_current - 1;
267 :
268 1141 : item->key.lexeme = palloc(hash_key.length);
269 1141 : memcpy(item->key.lexeme, hash_key.lexeme, hash_key.length);
270 : }
271 :
272 : /* lexeme_no is the number of elements processed (ie N) */
273 28817 : lexeme_no++;
274 :
275 : /* We prune the D structure after processing each bucket */
276 28817 : if (lexeme_no % bucket_width == 0)
277 : {
278 0 : prune_lexemes_hashtable(lexemes_tab, b_current);
279 0 : b_current++;
280 : }
281 :
282 : /* Advance to the next WordEntry in the tsvector */
283 28817 : curentryptr++;
284 : }
285 :
286 : /* If the vector was toasted, free the detoasted copy. */
287 508 : if (TSVectorGetDatum(vector) != value)
288 65 : pfree(vector);
289 : }
290 :
291 : /* We can only compute real stats if we found some non-null values. */
292 1 : if (null_cnt < samplerows)
293 : {
294 1 : int nonnull_cnt = samplerows - null_cnt;
295 : int i;
296 : TrackItem **sort_table;
297 : int track_len;
298 : int cutoff_freq;
299 : int minfreq,
300 : maxfreq;
301 :
302 1 : stats->stats_valid = true;
303 : /* Do the simple null-frac and average width stats */
304 1 : stats->stanullfrac = (double) null_cnt / (double) samplerows;
305 1 : stats->stawidth = total_width / (double) nonnull_cnt;
306 :
307 : /* Assume it's a unique column (see notes above) */
308 1 : stats->stadistinct = -1.0 * (1.0 - stats->stanullfrac);
309 :
310 : /*
311 : * Construct an array of the interesting hashtable items, that is,
312 : * those meeting the cutoff frequency (s - epsilon)*N. Also identify
313 : * the minimum and maximum frequencies among these items.
314 : *
315 : * Since epsilon = s/10 and bucket_width = 1/epsilon, the cutoff
316 : * frequency is 9*N / bucket_width.
317 : */
318 1 : cutoff_freq = 9 * lexeme_no / bucket_width;
319 :
320 1 : i = hash_get_num_entries(lexemes_tab); /* surely enough space */
321 1 : sort_table = (TrackItem **) palloc(sizeof(TrackItem *) * i);
322 :
323 1 : hash_seq_init(&scan_status, lexemes_tab);
324 1 : track_len = 0;
325 1 : minfreq = lexeme_no;
326 1 : maxfreq = 0;
327 1143 : while ((item = (TrackItem *) hash_seq_search(&scan_status)) != NULL)
328 : {
329 1141 : if (item->frequency > cutoff_freq)
330 : {
331 1053 : sort_table[track_len++] = item;
332 1053 : minfreq = Min(minfreq, item->frequency);
333 1053 : maxfreq = Max(maxfreq, item->frequency);
334 : }
335 : }
336 1 : Assert(track_len <= i);
337 :
338 : /* emit some statistics for debug purposes */
339 1 : elog(DEBUG3, "tsvector_stats: target # mces = %d, bucket width = %d, "
340 : "# lexemes = %d, hashtable size = %d, usable entries = %d",
341 : num_mcelem, bucket_width, lexeme_no, i, track_len);
342 :
343 : /*
344 : * If we obtained more lexemes than we really want, get rid of those
345 : * with least frequencies. The easiest way is to qsort the array into
346 : * descending frequency order and truncate the array.
347 : */
348 1 : if (num_mcelem < track_len)
349 : {
350 1 : qsort(sort_table, track_len, sizeof(TrackItem *),
351 : trackitem_compare_frequencies_desc);
352 : /* reset minfreq to the smallest frequency we're keeping */
353 1 : minfreq = sort_table[num_mcelem - 1]->frequency;
354 : }
355 : else
356 0 : num_mcelem = track_len;
357 :
358 : /* Generate MCELEM slot entry */
359 1 : if (num_mcelem > 0)
360 : {
361 : MemoryContext old_context;
362 : Datum *mcelem_values;
363 : float4 *mcelem_freqs;
364 :
365 : /*
366 : * We want to store statistics sorted on the lexeme value using
367 : * first length, then byte-for-byte comparison. The reason for
368 : * doing length comparison first is that we don't care about the
369 : * ordering so long as it's consistent, and comparing lengths
370 : * first gives us a chance to avoid a strncmp() call.
371 : *
372 : * This is different from what we do with scalar statistics --
373 : * they get sorted on frequencies. The rationale is that we
374 : * usually search through most common elements looking for a
375 : * specific value, so we can grab its frequency. When values are
376 : * presorted we can employ binary search for that. See
377 : * ts_selfuncs.c for a real usage scenario.
378 : */
379 1 : qsort(sort_table, num_mcelem, sizeof(TrackItem *),
380 : trackitem_compare_lexemes);
381 :
382 : /* Must copy the target values into anl_context */
383 1 : old_context = MemoryContextSwitchTo(stats->anl_context);
384 :
385 : /*
386 : * We sorted statistics on the lexeme value, but we want to be
387 : * able to find out the minimal and maximal frequency without
388 : * going through all the values. We keep those two extra
389 : * frequencies in two extra cells in mcelem_freqs.
390 : *
391 : * (Note: the MCELEM statistics slot definition allows for a third
392 : * extra number containing the frequency of nulls, but we don't
393 : * create that for a tsvector column, since null elements aren't
394 : * possible.)
395 : */
396 1 : mcelem_values = (Datum *) palloc(num_mcelem * sizeof(Datum));
397 1 : mcelem_freqs = (float4 *) palloc((num_mcelem + 2) * sizeof(float4));
398 :
399 : /*
400 : * See comments above about use of nonnull_cnt as the divisor for
401 : * the final frequency estimates.
402 : */
403 1001 : for (i = 0; i < num_mcelem; i++)
404 : {
405 1000 : TrackItem *item = sort_table[i];
406 :
407 2000 : mcelem_values[i] =
408 1000 : PointerGetDatum(cstring_to_text_with_len(item->key.lexeme,
409 : item->key.length));
410 1000 : mcelem_freqs[i] = (double) item->frequency / (double) nonnull_cnt;
411 : }
412 1 : mcelem_freqs[i++] = (double) minfreq / (double) nonnull_cnt;
413 1 : mcelem_freqs[i] = (double) maxfreq / (double) nonnull_cnt;
414 1 : MemoryContextSwitchTo(old_context);
415 :
416 1 : stats->stakind[0] = STATISTIC_KIND_MCELEM;
417 1 : stats->staop[0] = TextEqualOperator;
418 1 : stats->stanumbers[0] = mcelem_freqs;
419 : /* See above comment about two extra frequency fields */
420 1 : stats->numnumbers[0] = num_mcelem + 2;
421 1 : stats->stavalues[0] = mcelem_values;
422 1 : stats->numvalues[0] = num_mcelem;
423 : /* We are storing text values */
424 1 : stats->statypid[0] = TEXTOID;
425 1 : stats->statyplen[0] = -1; /* typlen, -1 for varlena */
426 1 : stats->statypbyval[0] = false;
427 1 : stats->statypalign[0] = 'i';
428 : }
429 : }
430 : else
431 : {
432 : /* We found only nulls; assume the column is entirely null */
433 0 : stats->stats_valid = true;
434 0 : stats->stanullfrac = 1.0;
435 0 : stats->stawidth = 0; /* "unknown" */
436 0 : stats->stadistinct = 0.0; /* "unknown" */
437 : }
438 :
439 : /*
440 : * We don't need to bother cleaning up any of our temporary palloc's. The
441 : * hashtable should also go away, as it used a child memory context.
442 : */
443 1 : }
444 :
445 : /*
446 : * A function to prune the D structure from the Lossy Counting algorithm.
447 : * Consult compute_tsvector_stats() for wider explanation.
448 : */
449 : static void
450 0 : prune_lexemes_hashtable(HTAB *lexemes_tab, int b_current)
451 : {
452 : HASH_SEQ_STATUS scan_status;
453 : TrackItem *item;
454 :
455 0 : hash_seq_init(&scan_status, lexemes_tab);
456 0 : while ((item = (TrackItem *) hash_seq_search(&scan_status)) != NULL)
457 : {
458 0 : if (item->frequency + item->delta <= b_current)
459 : {
460 0 : char *lexeme = item->key.lexeme;
461 :
462 0 : if (hash_search(lexemes_tab, (const void *) &item->key,
463 : HASH_REMOVE, NULL) == NULL)
464 0 : elog(ERROR, "hash table corrupted");
465 0 : pfree(lexeme);
466 : }
467 : }
468 0 : }
469 :
470 : /*
471 : * Hash functions for lexemes. They are strings, but not NULL terminated,
472 : * so we need a special hash function.
473 : */
474 : static uint32
475 28817 : lexeme_hash(const void *key, Size keysize)
476 : {
477 28817 : const LexemeHashKey *l = (const LexemeHashKey *) key;
478 :
479 28817 : return DatumGetUInt32(hash_any((const unsigned char *) l->lexeme,
480 : l->length));
481 : }
482 :
483 : /*
484 : * Matching function for lexemes, to be used in hashtable lookups.
485 : */
486 : static int
487 27676 : lexeme_match(const void *key1, const void *key2, Size keysize)
488 : {
489 : /* The keysize parameter is superfluous, the keys store their lengths */
490 27676 : return lexeme_compare(key1, key2);
491 : }
492 :
493 : /*
494 : * Comparison function for lexemes.
495 : */
496 : static int
497 37911 : lexeme_compare(const void *key1, const void *key2)
498 : {
499 37911 : const LexemeHashKey *d1 = (const LexemeHashKey *) key1;
500 37911 : const LexemeHashKey *d2 = (const LexemeHashKey *) key2;
501 :
502 : /* First, compare by length */
503 37911 : if (d1->length > d2->length)
504 0 : return 1;
505 37911 : else if (d1->length < d2->length)
506 0 : return -1;
507 : /* Lengths are equal, do a byte-by-byte comparison */
508 37911 : return strncmp(d1->lexeme, d2->lexeme, d1->length);
509 : }
510 :
511 : /*
512 : * qsort() comparator for sorting TrackItems on frequencies (descending sort)
513 : */
514 : static int
515 6090 : trackitem_compare_frequencies_desc(const void *e1, const void *e2)
516 : {
517 6090 : const TrackItem *const *t1 = (const TrackItem *const *) e1;
518 6090 : const TrackItem *const *t2 = (const TrackItem *const *) e2;
519 :
520 6090 : return (*t2)->frequency - (*t1)->frequency;
521 : }
522 :
523 : /*
524 : * qsort() comparator for sorting TrackItems on lexemes
525 : */
526 : static int
527 10235 : trackitem_compare_lexemes(const void *e1, const void *e2)
528 : {
529 10235 : const TrackItem *const *t1 = (const TrackItem *const *) e1;
530 10235 : const TrackItem *const *t2 = (const TrackItem *const *) e2;
531 :
532 10235 : return lexeme_compare(&(*t1)->key, &(*t2)->key);
533 : }
|