2017-03-09 46 views
2

我在PostgreSQL表中有一堆文本行,我试图找到常见的字符串。找到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_stat结合ts_headline但结果相当令人失望。

有什么想法?谢谢!

回答

1

没有即时使用的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) 
+0

感谢klin,这听起来像一个很好的方法,我会测试它! – Gab

1

如何像: SELECT * FROM a WHERE value LIKE '%movie theater%';

这会找个地方匹配该模式“电影院”的值列(以及可能包括之前或之后任何数量的字符)行。

+0

你好@Lionel,我不知道'电影院'是一个流行的字符串,我正在寻找的信息我正在寻找 – Gab

+0

。你能提供一些关于'popular string'的含义的更多信息吗?例如,你在寻找热门关键词,或者是短语?你在寻找最受欢迎的,还是有一个关键字或短语足够受欢迎的门槛? – Lionel

+0

像Twitter这样的流行关键词可以用于“趋势”。我的目标是找到最受欢迎的(例如前10名) – Gab