【问题标题】:Locate popular strings with PostgreSQL使用 PostgreSQL 查找流行的字符串
【发布时间】:2017-03-09 18:30:59
【问题描述】:

我在 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 结合使用,但结果非常令人失望。

有什么想法吗?谢谢!

【问题讨论】:

    标签: sql postgresql full-text-search postgresql-9.6 tsvector


    【解决方案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)
    

    【讨论】:

    • 谢谢klin,这听起来不错,我会测试一下!
    • 对于未来的访问者,如果您的字符串中包含分号,您可以使用to_tsvector(value) 而不是value::tsvector 来避免语法问题。
    【解决方案2】:

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

    这将在值列中的某处找到与模式“电影院”匹配的行(并且可以在其之前或之后包含任意数量的字符)。

    【讨论】:

    • 嗨@Lionel,我不知道movie theater 是一个流行的字符串,我正在搜索的信息
    • 我明白了。你能提供更多关于popular string 的意思的信息吗?例如,您是否在寻找流行的关键字或短语?您是在寻找最流行的,还是某个关键字或词组足够流行的阈值?
    • 流行的关键字,例如 Twitter 为“趋势”所做的。我的目标是找到最受欢迎的(例如前 10 名)
    猜你喜欢
    • 2012-06-30
    • 2023-03-15
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多