如何使用PostgreSQL实现更好的搜索?

时间:2017-05-01 06:09:27

标签: php postgresql

我正在使用ilike %name%在我的PostgreSQL数据库中搜索名称。

问题是匹配的名称太多而我的显示环境有限,所以我的搜索输出限制为20.本质上我可能会错过与输入字符串匹配的名称。

我将我的名字(名字,中间名,姓氏)存储在一列中。以下是搜索代码段:

select l_name from leader_info where (l_name ilike $1 or l_name ilike $2 or l_name ilike $3) 

我通常将任何输入的字符串拆分为3。 当我搜索如下名称时:

  汤姆沃尔夫

我得到的比赛如下:

  

塞缪尔·奥尔托姆,史蒂夫·沃尔托姆,山姆·汤姆默尔

我更喜欢只获得以下匹配:

  汤姆汉克斯,威尔弗雷德汤姆

1 个答案:

答案 0 :(得分:0)

可能是这种方式。

(例如只匹配单词“tom”和“steve”)

with t(col) as(
    select  'Samuel Ortom' union all
    select  'tom hanks' union all
    select  'Wilfred tom' union all
    select  'steve waltom' union all
    select  'A steven' union all
    select  'sam tommer'  
)

select * from t where 
to_tsvector(col) @@ to_tsquery('tom')
or
to_tsvector(col) @@ to_tsquery('steve');

或也可以是:... where to_tsvector(col) @@ to_tsquery('Tom | steve')

这是postgres full text search,也可以使用索引进行优化。