1 /*-------------------------------------------------------------------------
3 * Portions Copyright (c) 2004-2012, PostgreSQL Global Development Group
7 * Support full text search using bigrams.
8 * Author: NTT DATA Corporation
10 *-------------------------------------------------------------------------
18 #include "catalog/pg_type.h"
19 #include "tsearch/ts_locale.h"
20 #include "utils/array.h"
25 /* Last update date of pg_bigm */
26 #define BIGM_LAST_UPDATE "2013.11.22"
29 bool bigm_enable_recheck = false;
30 int bigm_gin_key_limit = 0;
31 double bigm_similarity_limit = 0.3;
32 char *bigm_last_update = NULL;
34 PG_FUNCTION_INFO_V1(show_bigm);
35 Datum show_bigm(PG_FUNCTION_ARGS);
37 PG_FUNCTION_INFO_V1(bigmtextcmp);
38 Datum bigmtextcmp(PG_FUNCTION_ARGS);
40 PG_FUNCTION_INFO_V1(likequery);
41 Datum likequery(PG_FUNCTION_ARGS);
43 PG_FUNCTION_INFO_V1(bigm_similarity);
44 Datum bigm_similarity(PG_FUNCTION_ARGS);
46 PG_FUNCTION_INFO_V1(bigm_similarity_op);
47 Datum bigm_similarity_op(PG_FUNCTION_ARGS);
55 /* Define custom GUC variables */
56 DefineCustomBoolVariable("pg_bigm.enable_recheck",
57 "Recheck that heap tuples fetched from index "
68 DefineCustomIntVariable("pg_bigm.gin_key_limit",
69 "Sets the maximum number of bi-gram keys allowed to "
70 "use for GIN index search.",
71 "Zero means no limit.",
81 DefineCustomRealVariable("pg_bigm.similarity_limit",
82 "Sets the similarity threshold used by the "
85 &bigm_similarity_limit,
94 /* Can't be set in postgresql.conf */
95 DefineCustomStringVariable("pg_bigm.last_update",
96 "Shows the last update date of pg_bigm.",
101 GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE,
106 EmitWarningsOnPlaceholders("pg_bigm");
115 comp_bigm(const void *a, const void *b, void *arg)
118 bool *haveDups = (bool *) arg;
129 unique_array(bigm *a, int len)
135 while (tmp - a < len)
136 if (CMPBIGM(tmp, curend))
140 memcpy(curend, tmp, BIGMSIZE);
146 return curend + 1 - a;
149 #define iswordchr(c) (!t_isspace(c))
152 * Finds first word in string, returns pointer to the word,
153 * endword points to the character after word
156 find_word(char *str, int lenstr, char **endword, int *charlen)
158 char *beginword = str;
160 while (beginword - str < lenstr && !iswordchr(beginword))
161 beginword += pg_mblen(beginword);
163 if (beginword - str >= lenstr)
166 *endword = beginword;
168 while (*endword - str < lenstr && iswordchr(*endword))
170 *endword += pg_mblen(*endword);
178 * The function is named compact_bigram to maintain consistency with pg_trgm,
179 * though it does not reduce multibyte characters to hash values like in
183 compact_bigram(bigm *bptr, char *str, int bytelen)
185 CPBIGM(bptr, str, bytelen);
189 * Adds bigrams from words (already padded).
192 make_bigrams(bigm *bptr, char *str, int bytelen, int charlen)
198 compact_bigram(bptr, ptr, pg_mblen(str));
204 if (bytelen > charlen)
206 /* Find multibyte character boundaries and call compact_bigram */
207 int lenfirst = pg_mblen(str),
208 lenlast = pg_mblen(str + lenfirst);
210 while ((ptr - str) + lenfirst + lenlast <= bytelen)
212 compact_bigram(bptr, ptr, lenfirst + lenlast);
218 lenlast = pg_mblen(ptr + lenfirst);
223 /* Fast path when there are no multibyte characters */
224 Assert(bytelen == charlen);
226 while (ptr - str < bytelen - 1 /* number of bigrams = strlen - 1 */ )
228 CPBIGM(bptr, ptr, 2);
238 generate_bigm(char *str, int slen)
249 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (slen / 2 + 1) *3);
250 SET_VARSIZE(bgm, VARHDRSZ);
252 if (slen + LPADDING + RPADDING < 2 || slen == 0)
257 buf = palloc(sizeof(char) * (slen + 4));
267 while ((bword = find_word(eword, slen - (eword - str), &eword, &charlen)) != NULL)
269 bytelen = eword - bword;
270 memcpy(buf + LPADDING, bword, bytelen);
272 buf[LPADDING + bytelen] = ' ';
273 buf[LPADDING + bytelen + 1] = ' ';
278 bptr = make_bigrams(bptr, buf, bytelen + LPADDING + RPADDING,
279 charlen + LPADDING + RPADDING);
284 if ((len = bptr - GETARR(bgm)) == 0)
289 bool haveDups = false;
291 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
293 len = unique_array(GETARR(bgm), len);
296 SET_VARSIZE(bgm, CALCGTSIZE(len));
302 * Extract the next non-wildcard part of a search string, ie, a word bounded
303 * by '_' or '%' meta-characters, non-word characters or string end.
305 * str: source string, of length lenstr bytes (need not be null-terminated)
306 * buf: where to return the substring (must be long enough)
307 * *bytelen: receives byte length of the found substring
308 * *charlen: receives character length of the found substring
310 * Returns pointer to end+1 of the found substring in the source string.
311 * Returns NULL if no word found (in which case buf, bytelen, charlen not set)
313 * If the found word is bounded by non-word characters or string boundaries
314 * then this function will include corresponding padding spaces into buf.
317 get_wildcard_part(const char *str, int lenstr,
318 char *buf, int *bytelen, int *charlen)
320 const char *beginword = str;
323 bool in_leading_wildcard_meta = false;
324 bool in_trailing_wildcard_meta = false;
325 bool in_escape = false;
329 * Find the first word character, remembering whether preceding character
330 * was wildcard meta-character. Note that the in_escape state persists
331 * from this loop to the next one, since we may exit at a word character
334 while (beginword - str < lenstr)
338 if (iswordchr(beginword))
341 in_leading_wildcard_meta = false;
345 if (ISESCAPECHAR(beginword))
347 else if (ISWILDCARDCHAR(beginword))
348 in_leading_wildcard_meta = true;
349 else if (iswordchr(beginword))
352 in_leading_wildcard_meta = false;
354 beginword += pg_mblen(beginword);
360 if (beginword - str >= lenstr)
364 * Add left padding spaces if preceding character wasn't wildcard
368 if (!in_leading_wildcard_meta)
383 * Copy data into buf until wildcard meta-character, non-word character or
384 * string boundary. Strip escapes during copy.
387 while (endword - str < lenstr)
389 clen = pg_mblen(endword);
392 if (iswordchr(endword))
394 memcpy(s, endword, clen);
401 * Back up endword to the escape character when stopping at
402 * an escaped char, so that subsequent get_wildcard_part will
403 * restart from the escape character. We assume here that
404 * escape chars are single-byte.
413 if (ISESCAPECHAR(endword))
415 else if (ISWILDCARDCHAR(endword))
417 in_trailing_wildcard_meta = true;
420 else if (iswordchr(endword))
422 memcpy(s, endword, clen);
433 * Add right padding spaces if next character isn't wildcard
436 if (!in_trailing_wildcard_meta)
455 * Generates bigrams for wildcard search string.
457 * Returns array of bigrams that must occur in any string that matches the
458 * wildcard string. For example, given pattern "a%bcd%" the bigrams
459 * " a", "bcd" would be extracted.
461 * Set 'removeDups' to true if duplicate bigrams are removed.
464 generate_wildcard_bigm(const char *str, int slen, bool *removeDups)
476 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (slen / 2 + 1) *3);
477 SET_VARSIZE(bgm, VARHDRSZ);
479 if (slen + LPADDING + RPADDING < 2 || slen == 0)
484 buf = palloc(sizeof(char) * (slen + 4));
487 * Extract bigrams from each substring extracted by get_wildcard_part.
490 while ((eword = get_wildcard_part(eword, slen - (eword - str),
491 buf, &bytelen, &charlen)) != NULL)
496 bptr = make_bigrams(bptr, buf, bytelen, charlen);
501 if ((len = bptr - GETARR(bgm)) == 0)
505 * Make bigrams unique.
509 bool haveDups = false;
511 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
515 len = unique_array(GETARR(bgm), len);
519 SET_VARSIZE(bgm, CALCGTSIZE(len));
525 show_bigm(PG_FUNCTION_ARGS)
527 text *in = PG_GETARG_TEXT_P(0);
534 bgm = generate_bigm(VARDATA(in), VARSIZE(in) - VARHDRSZ);
535 d = (Datum *) palloc(sizeof(Datum) * (1 + ARRNELEM(bgm)));
537 for (i = 0, ptr = GETARR(bgm); i < ARRNELEM(bgm); i++, ptr++)
539 text *item = cstring_to_text_with_len(ptr->str, ptr->bytelen);
540 d[i] = PointerGetDatum(item);
552 for (i = 0; i < ARRNELEM(bgm); i++)
553 pfree(DatumGetPointer(d[i]));
557 PG_FREE_IF_COPY(in, 0);
559 PG_RETURN_POINTER(a);
563 cnt_sml_bigm(BIGM *bgm1, BIGM *bgm2)
574 len1 = ARRNELEM(bgm1);
575 len2 = ARRNELEM(bgm2);
577 /* explicit test is needed to avoid 0/0 division when both lengths are 0 */
578 if (len1 <= 0 || len2 <= 0)
581 while (ptr1 - GETARR(bgm1) < len1 && ptr2 - GETARR(bgm2) < len2)
583 int res = CMPBIGM(ptr1, ptr2);
598 return ((float4) count) / ((float4) (len1 + len2 - count));
600 return ((float4) count) / ((float4) ((len1 > len2) ? len1 : len2));
605 bigm_similarity(PG_FUNCTION_ARGS)
607 text *in1 = PG_GETARG_TEXT_P(0);
608 text *in2 = PG_GETARG_TEXT_P(1);
613 bgm1 = generate_bigm(VARDATA(in1), VARSIZE(in1) - VARHDRSZ);
614 bgm2 = generate_bigm(VARDATA(in2), VARSIZE(in2) - VARHDRSZ);
616 res = cnt_sml_bigm(bgm1, bgm2);
620 PG_FREE_IF_COPY(in1, 0);
621 PG_FREE_IF_COPY(in2, 1);
623 PG_RETURN_FLOAT4(res);
627 bigm_similarity_op(PG_FUNCTION_ARGS)
629 float4 res = DatumGetFloat4(DirectFunctionCall2(bigm_similarity,
631 PG_GETARG_DATUM(1)));
633 PG_RETURN_BOOL(res >= (float4) bigm_similarity_limit);
637 likequery(PG_FUNCTION_ARGS)
639 text *query = PG_GETARG_TEXT_PP(0);
647 str = VARDATA_ANY(query);
648 len = VARSIZE_ANY_EXHDR(query);
653 result = (text *) palloc(len * 2 + 2 + VARHDRSZ);
654 rp = VARDATA(result);
657 for (sp = str; (sp - str) < len;)
659 if (ISWILDCARDCHAR(sp) || ISESCAPECHAR(sp))
664 else if (IS_HIGHBIT_SET(*sp))
666 mblen = pg_mblen(sp);
667 memcpy(rp, sp, mblen);
676 SET_VARSIZE(result, rp - VARDATA(result) + VARHDRSZ);
678 PG_RETURN_TEXT_P(result);
682 bigmstrcmp(char *arg1, int len1, char *arg2, int len2)
685 int len = Min(len1, len2);
687 for (i = 0; i < len; i++, arg1++, arg2++)
697 return (len1 == len2) ? 0 : ((len1 < len2) ? -1 : 1);
701 bigmtextcmp(PG_FUNCTION_ARGS)
703 text *arg1 = PG_GETARG_TEXT_PP(0);
704 text *arg2 = PG_GETARG_TEXT_PP(1);
705 char *a1p = VARDATA_ANY(arg1);
706 char *a2p = VARDATA_ANY(arg2);
707 int len1 = VARSIZE_ANY_EXHDR(arg1);
708 int len2 = VARSIZE_ANY_EXHDR(arg2);
710 PG_RETURN_INT32(bigmstrcmp(a1p, len1, a2p, len2));