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)
288 * Make bigrams unique.
292 bool haveDups = false;
294 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
296 len = unique_array(GETARR(bgm), len);
299 SET_VARSIZE(bgm, CALCGTSIZE(len));
305 * Extract the next non-wildcard part of a search string, ie, a word bounded
306 * by '_' or '%' meta-characters, non-word characters or string end.
308 * str: source string, of length lenstr bytes (need not be null-terminated)
309 * buf: where to return the substring (must be long enough)
310 * *bytelen: receives byte length of the found substring
311 * *charlen: receives character length of the found substring
313 * Returns pointer to end+1 of the found substring in the source string.
314 * Returns NULL if no word found (in which case buf, bytelen, charlen not set)
316 * If the found word is bounded by non-word characters or string boundaries
317 * then this function will include corresponding padding spaces into buf.
320 get_wildcard_part(const char *str, int lenstr,
321 char *buf, int *bytelen, int *charlen)
323 const char *beginword = str;
326 bool in_leading_wildcard_meta = false;
327 bool in_trailing_wildcard_meta = false;
328 bool in_escape = false;
332 * Find the first word character, remembering whether preceding character
333 * was wildcard meta-character. Note that the in_escape state persists
334 * from this loop to the next one, since we may exit at a word character
337 while (beginword - str < lenstr)
341 if (iswordchr(beginword))
344 in_leading_wildcard_meta = false;
348 if (ISESCAPECHAR(beginword))
350 else if (ISWILDCARDCHAR(beginword))
351 in_leading_wildcard_meta = true;
352 else if (iswordchr(beginword))
355 in_leading_wildcard_meta = false;
357 beginword += pg_mblen(beginword);
363 if (beginword - str >= lenstr)
367 * Add left padding spaces if preceding character wasn't wildcard
371 if (!in_leading_wildcard_meta)
386 * Copy data into buf until wildcard meta-character, non-word character or
387 * string boundary. Strip escapes during copy.
390 while (endword - str < lenstr)
392 clen = pg_mblen(endword);
395 if (iswordchr(endword))
397 memcpy(s, endword, clen);
404 * Back up endword to the escape character when stopping at
405 * an escaped char, so that subsequent get_wildcard_part will
406 * restart from the escape character. We assume here that
407 * escape chars are single-byte.
416 if (ISESCAPECHAR(endword))
418 else if (ISWILDCARDCHAR(endword))
420 in_trailing_wildcard_meta = true;
423 else if (iswordchr(endword))
425 memcpy(s, endword, clen);
436 * Add right padding spaces if next character isn't wildcard
439 if (!in_trailing_wildcard_meta)
458 * Generates bigrams for wildcard search string.
460 * Returns array of bigrams that must occur in any string that matches the
461 * wildcard string. For example, given pattern "a%bcd%" the bigrams
462 * " a", "bcd" would be extracted.
464 * Set 'removeDups' to true if duplicate bigrams are removed.
467 generate_wildcard_bigm(const char *str, int slen, bool *removeDups)
479 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (slen / 2 + 1) *3);
480 SET_VARSIZE(bgm, VARHDRSZ);
482 if (slen + LPADDING + RPADDING < 2 || slen == 0)
487 buf = palloc(sizeof(char) * (slen + 4));
490 * Extract bigrams from each substring extracted by get_wildcard_part.
493 while ((eword = get_wildcard_part(eword, slen - (eword - str),
494 buf, &bytelen, &charlen)) != NULL)
499 bptr = make_bigrams(bptr, buf, bytelen, charlen);
504 if ((len = bptr - GETARR(bgm)) == 0)
508 * Make bigrams unique.
512 bool haveDups = false;
514 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
518 len = unique_array(GETARR(bgm), len);
522 SET_VARSIZE(bgm, CALCGTSIZE(len));
528 show_bigm(PG_FUNCTION_ARGS)
530 text *in = PG_GETARG_TEXT_P(0);
537 bgm = generate_bigm(VARDATA(in), VARSIZE(in) - VARHDRSZ);
538 d = (Datum *) palloc(sizeof(Datum) * (1 + ARRNELEM(bgm)));
540 for (i = 0, ptr = GETARR(bgm); i < ARRNELEM(bgm); i++, ptr++)
542 text *item = cstring_to_text_with_len(ptr->str, ptr->bytelen);
543 d[i] = PointerGetDatum(item);
555 for (i = 0; i < ARRNELEM(bgm); i++)
556 pfree(DatumGetPointer(d[i]));
560 PG_FREE_IF_COPY(in, 0);
562 PG_RETURN_POINTER(a);
566 cnt_sml_bigm(BIGM *bgm1, BIGM *bgm2)
577 len1 = ARRNELEM(bgm1);
578 len2 = ARRNELEM(bgm2);
580 /* explicit test is needed to avoid 0/0 division when both lengths are 0 */
581 if (len1 <= 0 || len2 <= 0)
584 while (ptr1 - GETARR(bgm1) < len1 && ptr2 - GETARR(bgm2) < len2)
586 int res = CMPBIGM(ptr1, ptr2);
601 return ((float4) count) / ((float4) (len1 + len2 - count));
603 return ((float4) count) / ((float4) ((len1 > len2) ? len1 : len2));
608 bigm_similarity(PG_FUNCTION_ARGS)
610 text *in1 = PG_GETARG_TEXT_P(0);
611 text *in2 = PG_GETARG_TEXT_P(1);
616 bgm1 = generate_bigm(VARDATA(in1), VARSIZE(in1) - VARHDRSZ);
617 bgm2 = generate_bigm(VARDATA(in2), VARSIZE(in2) - VARHDRSZ);
619 res = cnt_sml_bigm(bgm1, bgm2);
623 PG_FREE_IF_COPY(in1, 0);
624 PG_FREE_IF_COPY(in2, 1);
626 PG_RETURN_FLOAT4(res);
630 bigm_similarity_op(PG_FUNCTION_ARGS)
632 float4 res = DatumGetFloat4(DirectFunctionCall2(bigm_similarity,
634 PG_GETARG_DATUM(1)));
636 PG_RETURN_BOOL(res >= (float4) bigm_similarity_limit);
640 likequery(PG_FUNCTION_ARGS)
642 text *query = PG_GETARG_TEXT_PP(0);
650 str = VARDATA_ANY(query);
651 len = VARSIZE_ANY_EXHDR(query);
656 result = (text *) palloc(len * 2 + 2 + VARHDRSZ);
657 rp = VARDATA(result);
660 for (sp = str; (sp - str) < len;)
662 if (ISWILDCARDCHAR(sp) || ISESCAPECHAR(sp))
667 else if (IS_HIGHBIT_SET(*sp))
669 mblen = pg_mblen(sp);
670 memcpy(rp, sp, mblen);
679 SET_VARSIZE(result, rp - VARDATA(result) + VARHDRSZ);
681 PG_RETURN_TEXT_P(result);
685 bigmstrcmp(char *arg1, int len1, char *arg2, int len2)
688 int len = Min(len1, len2);
690 for (i = 0; i < len; i++, arg1++, arg2++)
700 return (len1 == len2) ? 0 : ((len1 < len2) ? -1 : 1);
704 bigmtextcmp(PG_FUNCTION_ARGS)
706 text *arg1 = PG_GETARG_TEXT_PP(0);
707 text *arg2 = PG_GETARG_TEXT_PP(1);
708 char *a1p = VARDATA_ANY(arg1);
709 char *a2p = VARDATA_ANY(arg2);
710 int len1 = VARSIZE_ANY_EXHDR(arg1);
711 int len2 = VARSIZE_ANY_EXHDR(arg2);
713 PG_RETURN_INT32(bigmstrcmp(a1p, len1, a2p, len2));