使用 PostgreSQL 定位流行的字符串

Locate popular strings with PostgreSQL

我在 PostgreSQL table 中有一堆文本行,我正在尝试查找常用字符串。

例如,假设我有一个基本的 table,例如:

CREATE TABLE a (id serial, value text);
INSERT INTO a (value) VALUES
    ('I go to the movie theater'), 
    ('New movie theater releases'), 
    ('Coming out this week at your local movie theater'),
    ('New exposition about learning disabilities at the children museum'),
    ('The genius found in learning disabilities')
;

我试图在所有行中找到 movie theaterlearning disabilities 等流行字符串(目标是显示 "trending" 字符串之王的列表,如 Twitter "Trends")

我使用全文搜索,我尝试将 ts_statts_headline 结合使用,但结果非常令人失望。

有什么想法吗?谢谢!

怎么样: SELECT * FROM a WHERE value LIKE '%movie theater%';

这会在值列的某处找到与模式 'movie theater' 匹配的行(并且可以在其前后包含任意数量的字符)。

没有现成的 Posgres 文本搜索功能来查找最流行的短语。对于双词短语,您可以使用 ts_stat() 找到最流行的词,消除助词、介词等,并交叉连接这些词以找到最流行的词对。

对于实际数据,您可能希望更改标记为 --> parameter. 的值。对于较大的数据集,查询可能会非常昂贵。

with popular_words as (
    select word
    from ts_stat('select value::tsvector from a')
    where nentry > 1                                --> parameter
    and not word in ('to', 'the', 'at', 'in', 'a')  --> parameter
)
select concat_ws(' ', a1.word, a2.word) phrase, count(*) 
from popular_words as a1
cross join popular_words as a2
cross join a
where value ilike format('%%%s %s%%', a1.word, a2.word)
group by 1
having count(*) > 1                                 --> parameter
order by 2 desc;


        phrase         | count 
-----------------------+-------
 movie theater         |     3
 learning disabilities |     2
(2 rows)