【问题标题】:How to create a trigram or ngram word with Postgres如何使用 Postgres 创建 trigram 或 ngram 单词
【发布时间】:2020-11-22 11:32:13
【问题描述】:

我正在尝试使用 Postgres 创建基于三元词的搜索。这个想法是实现一个简单的did you mean

我想要一张包含三字词而不是字符串的表格。我知道 Postgres 为字符串提供三元组(pg_tgrm),但我想做到这一点:

` roses beautiful red colar sun`

三字词

[`roses beautiful red`, `beautiful red colar`, `red colar sun`]

如何在查询中实现这一目标的最有效和最快捷的方式。

Select column from table -- transforming into the above 每行?

我试过了:

with words as (
 select unnest(regexp_split_to_array(`roses beautiful red colar sun`,'\s+')) as c from col
)
select c1.c || c2.c
from words c1
cross join words c2;

但我不知道如何将交叉联接用于更高级的场景。

【问题讨论】:

    标签: postgresql trigram


    【解决方案1】:

    您可以通过以下功能使用 PostgreSQL 全文搜索的强大功能:

    CREATE FUNCTION phrase_trigram(regconfig, text) RETURNS tsquery
       LANGUAGE plpgsql AS
    $$DECLARE
       words text[];
       i integer;
       result tsquery;
       q tsquery;
    BEGIN
       /* split the string into an array of words */
       words := regexp_split_to_array($2, '[[:space:]]+');
    
       FOR i IN 1..cardinality(words) - 2 LOOP
          /* a phrase consisting of three consecutive words */
          q := phraseto_tsquery($1, array_to_string(words[i:i+2], ' '));
          IF result IS NULL THEN
             result := q;
          ELSE
             /* append with "or" */
             result := result || q;
          END IF;
       END LOOP;
    
       RETURN result;
    END;$$;
    

    这会构建一个全文搜索查询,用于测试您想要的“三字”短语。

    像这样使用它:

    SELECT to_tsvector('english', 'a text containing beautiful red colar')
           @@ phrase_trigram('english', 'roses beautiful red colar sun'::text);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      • 2018-07-21
      • 1970-01-01
      • 2018-02-04
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多