Postgres搜索策略

时间:2017-04-25 14:20:41

标签: sql postgresql search plpgsql

我有分段的数据: -

  • 邮政编码
  • 地方

我的目标是构建一个搜索函数,该函数将按优先顺序查找使用上述分段给出的任何文本。即。首先查找邮政编码,然后是城镇然后放置

这可以在没有完全扫描邮政编码/城镇之前有效地完成吗?我可以确定文本是使用REGEX的邮政编码,城镇和地方更难。

我很高兴将其编码为PLPGSQL函数,并在这些方面采取了一些策略: -

WITH POSTCODES AS (

    SELECT postcode FROM postcode WHERE postcode ~* $1

), TOWNS AS (

    SELECT town FROM towns WHERE (SELECT * FROM POSTCODES LIMIT 1) IS NULL AND town ~* $1 

), PLACES AS (

   SELECT place FROM places WHERE (SELECT * FROM TOWNS LIMIT 1) IS NULL AND place ~* $1

) 
SELECT postcode as res FROM POSTCODE
UNION ALL 
SELECT town as res FROM TOWNS
UNION ALL
SELECT place as res FROM PLACES 

1 个答案:

答案 0 :(得分:0)

我使用权重解决了这个问题,并将我的数据合并到一个包含POSTCODE,TOWN,PLACE列的表中,我的数据允许我这样做。

然后我可以创建一个额外的列 tsv : -

setweight(to_tsvector(COALESCE(postcode,'')), 'A') ||
setweight(to_tsvector(COALESCE(town,''))    , 'B') ||
setweight(to_tsvector(COALESCE(place,''))   , 'C')

搜索: -

 WHERE (tsv @@ plainto_tsquery('SN1 3PF'))