【问题标题】:Searching a super string in a list of strings - POSTGRES在字符串列表中搜索超级字符串 - POSTGRES
【发布时间】:2018-11-26 13:19:23
【问题描述】:

我不确定我的问题措辞是否正确。但是如何在 POSTGRES 中搜索一个字符串,从而得到如下结果。

要搜索的字符串:

谷歌私人有限公司

表格中的数据

symbol, company name
GOOG, Google Ltd
FACEBOOK, Facebook Corp
APPLE, Apple Inc
DELL, Dell Ltd

如何返回搜索结果

谷歌,谷歌有限公司

,逻辑是根据匹配的最大单词返回结果。

我正在研究 POSTGRES 中的全文搜索选项,我可以理解使用 to_tsvector 的标记化。但我不确定在此之后如何进行。这种搜索方式可行吗?

【问题讨论】:

    标签: sql postgresql search full-text-search


    【解决方案1】:

    我不确定您是否需要对此进行全文搜索——这取决于性能。还有其他方法,比如打断列,输入单词,直接在上面匹配。

    这是一种使用regexp_matches()的方法:

    select v.*,
           (select count(*) from regexp_matches(symbol || ' ' || company, replace('Google Pvt Ltd', ' ', '|'), 'g')) as matches
    from (values ('GOOG', 'Google Ltd'),
                 ('FACEBOOK', 'Facebook Corp'),
                 ('APPLE', 'Apple Inc'),
                 ('DELL', 'Dell Ltd')
        ) v(symbol, company)
    order by matches desc
    fetch first 1 row only;
    

    【讨论】:

    • 这可行,但在某些情况下,它没有给我任何结果或意想不到的结果。
    【解决方案2】:

    您可以使用pg_trgm 扩展名。

    create extension if not exists pg_trgm;
    
    with my_table(symbol, company_name) as (
    values
        ('GOOG', 'Google Ltd'),
        ('FACEBOOK', 'Facebook Corp'),
        ('APPLE', 'Apple Inc'),
        ('DELL', 'Dell Ltd')
    )
    
    select *, similarity(company_name, 'Google Pvt Ltd')
    from my_table
    order by similarity desc;
    
      symbol  | company_name  | similarity 
    ----------+---------------+------------
     GOOG     | Google Ltd    |   0.733333
     DELL     | Dell Ltd      |        0.2
     APPLE    | Apple Inc     |  0.0416667
     FACEBOOK | Facebook Corp |          0
    (4 rows)
    

    您可以定义当前相似度阈值,只需使用% 运算符,例如:

    select set_limit(0.6);
    
    select *
    from my_table
    where company_name % 'Google Pvt Ltd'
    
     symbol | company_name 
    --------+--------------
     GOOG   | Google Ltd
    (1 row) 
    

    【讨论】:

    • 这符合我的要求。谢谢!
    • @Sammy 。 . .这是 - 毫无疑问 - 解决您的问题的最佳方法。但是您的实际问题是“匹配的最大字数”,而这并没有做到最大字数;它测量相似度。
    • 从概念上讲,我的感觉是一样的。也许我没有正确地用词。但它给了我结果。但是我们可以设置每个查询的限制而不是全局吗?
    • 您可以互换使用函数和运算符,例如where similarity(company_name, 'Google Pvt Ltd') > 0.6 而不是 where company_name % 'Google Pvt Ltd'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    相关资源
    最近更新 更多