1 /*-------------------------------------------------------------------------
3 * Portions Copyright (c) 2004-2012, PostgreSQL Global Development Group
4 * Portions Copyright (c) 2013-2015, NTT DATA Corporation
8 * Support full text search using bigrams.
9 * Author: NTT DATA Corporation
11 *-------------------------------------------------------------------------
19 #include "catalog/pg_type.h"
20 #include "tsearch/ts_locale.h"
21 #include "utils/array.h"
26 /* Last update date of pg_bigm */
27 #define BIGM_LAST_UPDATE "2013.11.22"
30 bool bigm_enable_recheck = false;
31 int bigm_gin_key_limit = 0;
32 double bigm_similarity_limit = 0.3;
33 char *bigm_last_update = NULL;
35 PG_FUNCTION_INFO_V1(show_bigm);
36 PG_FUNCTION_INFO_V1(bigmtextcmp);
37 PG_FUNCTION_INFO_V1(likequery);
38 PG_FUNCTION_INFO_V1(bigm_similarity);
39 PG_FUNCTION_INFO_V1(bigm_similarity_op);
42 * The function prototypes are created as a part of PG_FUNCTION_INFO_V1
43 * macro since 9.4, and hence the declaration of the function prototypes
44 * here is necessary only for 9.3 or before.
46 #if PG_VERSION_NUM < 90400
47 Datum show_bigm(PG_FUNCTION_ARGS);
48 Datum bigmtextcmp(PG_FUNCTION_ARGS);
49 Datum likequery(PG_FUNCTION_ARGS);
50 Datum bigm_similarity(PG_FUNCTION_ARGS);
51 Datum bigm_similarity_op(PG_FUNCTION_ARGS);
60 /* Define custom GUC variables */
61 DefineCustomBoolVariable("pg_bigm.enable_recheck",
62 "Recheck that heap tuples fetched from index "
73 DefineCustomIntVariable("pg_bigm.gin_key_limit",
74 "Sets the maximum number of bi-gram keys allowed to "
75 "use for GIN index search.",
76 "Zero means no limit.",
86 DefineCustomRealVariable("pg_bigm.similarity_limit",
87 "Sets the similarity threshold used by the "
90 &bigm_similarity_limit,
99 /* Can't be set in postgresql.conf */
100 DefineCustomStringVariable("pg_bigm.last_update",
101 "Shows the last update date of pg_bigm.",
106 GUC_REPORT | GUC_NOT_IN_SAMPLE | GUC_DISALLOW_IN_FILE,
111 EmitWarningsOnPlaceholders("pg_bigm");
120 comp_bigm(const void *a, const void *b, void *arg)
123 bool *haveDups = (bool *) arg;
134 unique_array(bigm *a, int len)
140 while (tmp - a < len)
141 if (CMPBIGM(tmp, curend))
145 memcpy(curend, tmp, BIGMSIZE);
151 return curend + 1 - a;
154 #define iswordchr(c) (!t_isspace(c))
157 * Finds first word in string, returns pointer to the word,
158 * endword points to the character after word
161 find_word(char *str, int lenstr, char **endword, int *charlen)
163 char *beginword = str;
165 while (beginword - str < lenstr && !iswordchr(beginword))
166 beginword += pg_mblen(beginword);
168 if (beginword - str >= lenstr)
171 *endword = beginword;
173 while (*endword - str < lenstr && iswordchr(*endword))
175 *endword += pg_mblen(*endword);
183 * The function is named compact_bigram to maintain consistency with pg_trgm,
184 * though it does not reduce multibyte characters to hash values like in
188 compact_bigram(bigm *bptr, char *str, int bytelen)
190 CPBIGM(bptr, str, bytelen);
194 * Adds bigrams from words (already padded).
197 make_bigrams(bigm *bptr, char *str, int bytelen, int charlen)
203 compact_bigram(bptr, ptr, pg_mblen(str));
209 if (bytelen > charlen)
211 /* Find multibyte character boundaries and call compact_bigram */
212 int lenfirst = pg_mblen(str),
213 lenlast = pg_mblen(str + lenfirst);
215 while ((ptr - str) + lenfirst + lenlast <= bytelen)
217 compact_bigram(bptr, ptr, lenfirst + lenlast);
223 lenlast = pg_mblen(ptr + lenfirst);
228 /* Fast path when there are no multibyte characters */
229 Assert(bytelen == charlen);
231 while (ptr - str < bytelen - 1 /* number of bigrams = strlen - 1 */ )
233 CPBIGM(bptr, ptr, 2);
243 generate_bigm(char *str, int slen)
254 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (Size) (slen / 2 + 1) * 3);
255 SET_VARSIZE(bgm, VARHDRSZ);
257 if (slen + LPADDING + RPADDING < 2 || slen == 0)
262 buf = palloc(sizeof(char) * (slen + 4));
272 while ((bword = find_word(eword, slen - (eword - str), &eword, &charlen)) != NULL)
274 bytelen = eword - bword;
275 memcpy(buf + LPADDING, bword, bytelen);
277 buf[LPADDING + bytelen] = ' ';
278 buf[LPADDING + bytelen + 1] = ' ';
283 bptr = make_bigrams(bptr, buf, bytelen + LPADDING + RPADDING,
284 charlen + LPADDING + RPADDING);
289 if ((len = bptr - GETARR(bgm)) == 0)
293 * Make bigrams unique.
297 bool haveDups = false;
299 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
301 len = unique_array(GETARR(bgm), len);
304 SET_VARSIZE(bgm, CALCGTSIZE(len));
310 * Extract the next non-wildcard part of a search string, ie, a word bounded
311 * by '_' or '%' meta-characters, non-word characters or string end.
313 * str: source string, of length lenstr bytes (need not be null-terminated)
314 * buf: where to return the substring (must be long enough)
315 * *bytelen: receives byte length of the found substring
316 * *charlen: receives character length of the found substring
318 * Returns pointer to end+1 of the found substring in the source string.
319 * Returns NULL if no word found (in which case buf, bytelen, charlen not set)
321 * If the found word is bounded by non-word characters or string boundaries
322 * then this function will include corresponding padding spaces into buf.
325 get_wildcard_part(const char *str, int lenstr,
326 char *buf, int *bytelen, int *charlen)
328 const char *beginword = str;
331 bool in_leading_wildcard_meta = false;
332 bool in_trailing_wildcard_meta = false;
333 bool in_escape = false;
337 * Find the first word character, remembering whether preceding character
338 * was wildcard meta-character. Note that the in_escape state persists
339 * from this loop to the next one, since we may exit at a word character
342 while (beginword - str < lenstr)
346 if (iswordchr(beginword))
349 in_leading_wildcard_meta = false;
353 if (ISESCAPECHAR(beginword))
355 else if (ISWILDCARDCHAR(beginword))
356 in_leading_wildcard_meta = true;
357 else if (iswordchr(beginword))
360 in_leading_wildcard_meta = false;
362 beginword += pg_mblen(beginword);
368 if (beginword - str >= lenstr)
372 * Add left padding spaces if preceding character wasn't wildcard
376 if (!in_leading_wildcard_meta)
391 * Copy data into buf until wildcard meta-character, non-word character or
392 * string boundary. Strip escapes during copy.
395 while (endword - str < lenstr)
397 clen = pg_mblen(endword);
400 if (iswordchr(endword))
402 memcpy(s, endword, clen);
409 * Back up endword to the escape character when stopping at
410 * an escaped char, so that subsequent get_wildcard_part will
411 * restart from the escape character. We assume here that
412 * escape chars are single-byte.
421 if (ISESCAPECHAR(endword))
423 else if (ISWILDCARDCHAR(endword))
425 in_trailing_wildcard_meta = true;
428 else if (iswordchr(endword))
430 memcpy(s, endword, clen);
441 * Add right padding spaces if next character isn't wildcard
444 if (!in_trailing_wildcard_meta)
463 * Generates bigrams for wildcard search string.
465 * Returns array of bigrams that must occur in any string that matches the
466 * wildcard string. For example, given pattern "a%bcd%" the bigrams
467 * " a", "bcd" would be extracted.
469 * Set 'removeDups' to true if duplicate bigrams are removed.
472 generate_wildcard_bigm(const char *str, int slen, bool *removeDups)
484 bgm = (BIGM *) palloc(VARHDRSZ + sizeof(bigm) * (Size) (slen / 2 + 1) * 3);
485 SET_VARSIZE(bgm, VARHDRSZ);
487 if (slen + LPADDING + RPADDING < 2 || slen == 0)
492 buf = palloc(sizeof(char) * (slen + 4));
495 * Extract bigrams from each substring extracted by get_wildcard_part.
498 while ((eword = get_wildcard_part(eword, slen - (eword - str),
499 buf, &bytelen, &charlen)) != NULL)
504 bptr = make_bigrams(bptr, buf, bytelen, charlen);
509 if ((len = bptr - GETARR(bgm)) == 0)
513 * Make bigrams unique.
517 bool haveDups = false;
519 qsort_arg((void *) GETARR(bgm), len, sizeof(bigm), comp_bigm, (void *) &haveDups);
523 len = unique_array(GETARR(bgm), len);
527 SET_VARSIZE(bgm, CALCGTSIZE(len));
533 show_bigm(PG_FUNCTION_ARGS)
535 text *in = PG_GETARG_TEXT_P(0);
542 bgm = generate_bigm(VARDATA(in), VARSIZE(in) - VARHDRSZ);
543 d = (Datum *) palloc(sizeof(Datum) * (1 + ARRNELEM(bgm)));
545 for (i = 0, ptr = GETARR(bgm); i < ARRNELEM(bgm); i++, ptr++)
547 text *item = cstring_to_text_with_len(ptr->str, ptr->bytelen);
548 d[i] = PointerGetDatum(item);
560 for (i = 0; i < ARRNELEM(bgm); i++)
561 pfree(DatumGetPointer(d[i]));
565 PG_FREE_IF_COPY(in, 0);
567 PG_RETURN_POINTER(a);
571 cnt_sml_bigm(BIGM *bgm1, BIGM *bgm2)
582 len1 = ARRNELEM(bgm1);
583 len2 = ARRNELEM(bgm2);
585 /* explicit test is needed to avoid 0/0 division when both lengths are 0 */
586 if (len1 <= 0 || len2 <= 0)
589 while (ptr1 - GETARR(bgm1) < len1 && ptr2 - GETARR(bgm2) < len2)
591 int res = CMPBIGM(ptr1, ptr2);
606 return ((float4) count) / ((float4) (len1 + len2 - count));
608 return ((float4) count) / ((float4) ((len1 > len2) ? len1 : len2));
613 bigm_similarity(PG_FUNCTION_ARGS)
615 text *in1 = PG_GETARG_TEXT_P(0);
616 text *in2 = PG_GETARG_TEXT_P(1);
621 bgm1 = generate_bigm(VARDATA(in1), VARSIZE(in1) - VARHDRSZ);
622 bgm2 = generate_bigm(VARDATA(in2), VARSIZE(in2) - VARHDRSZ);
624 res = cnt_sml_bigm(bgm1, bgm2);
628 PG_FREE_IF_COPY(in1, 0);
629 PG_FREE_IF_COPY(in2, 1);
631 PG_RETURN_FLOAT4(res);
635 bigm_similarity_op(PG_FUNCTION_ARGS)
637 float4 res = DatumGetFloat4(DirectFunctionCall2(bigm_similarity,
639 PG_GETARG_DATUM(1)));
641 PG_RETURN_BOOL(res >= (float4) bigm_similarity_limit);
645 likequery(PG_FUNCTION_ARGS)
647 text *query = PG_GETARG_TEXT_PP(0);
655 str = VARDATA_ANY(query);
656 len = VARSIZE_ANY_EXHDR(query);
661 result = (text *) palloc((Size) len * 2 + 2 + VARHDRSZ);
662 rp = VARDATA(result);
665 for (sp = str; (sp - str) < len;)
667 if (ISWILDCARDCHAR(sp) || ISESCAPECHAR(sp))
672 else if (IS_HIGHBIT_SET(*sp))
674 mblen = pg_mblen(sp);
675 memcpy(rp, sp, mblen);
684 SET_VARSIZE(result, rp - VARDATA(result) + VARHDRSZ);
686 PG_RETURN_TEXT_P(result);
690 bigmstrcmp(char *arg1, int len1, char *arg2, int len2)
693 int len = Min(len1, len2);
695 for (i = 0; i < len; i++, arg1++, arg2++)
705 return (len1 == len2) ? 0 : ((len1 < len2) ? -1 : 1);
709 bigmtextcmp(PG_FUNCTION_ARGS)
711 text *arg1 = PG_GETARG_TEXT_PP(0);
712 text *arg2 = PG_GETARG_TEXT_PP(1);
713 char *a1p = VARDATA_ANY(arg1);
714 char *a2p = VARDATA_ANY(arg2);
715 int len1 = VARSIZE_ANY_EXHDR(arg1);
716 int len2 = VARSIZE_ANY_EXHDR(arg2);
718 PG_RETURN_INT32(bigmstrcmp(a1p, len1, a2p, len2));