我在一个PostgreSQL表中有一堆文本行,我正在尝试寻找公共字符串。
例如,假设我有一个基本表,比如:

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(目标是显示一个“趋势”字符串列表,就像Twitter中的“趋势”一样)
我使用全文搜索,并且尝试将ts_statts_headline结合使用,但是结果非常令人失望。
有什么想法吗?谢谢!

最佳答案

没有现成的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)

关于sql - 使用PostgreSQL找到流行的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42702888/

10-10 05:34