【问题标题】:How to create index in postgresql for regexp_matches?如何在 postgresql 中为 regexp_matches 创建索引?
【发布时间】:2020-06-10 01:18:45
【问题描述】:

我有一张桌子产品

product_id | desciption                                     
============================================================
322919     | text {add}185{/add} text                       
322920     | text {add}184{/add} text {add}185{/add} text   
322921     | text {add}185{/add} text {add}187{/add} text

like的sql查询很慢

SELECT product_id, desciption 
FROM product 
WHERE LOWER(desciption) like '%{add}185{/add}%'
> Time: 340,159s

我只需要一个索引来搜索 {add}185{/add} 表达式。 即需要为这个表建立一个索引

SELECT product_id, regexp_matches (desciption, '(\{add\}\d+\{\/add\})', 'g') 
FROM product 

返回:

product_id | regexp_matches 
================================================================================
322919     | {"{add}185{/add}"}
322920     | {"{add}184{/add}"}
322920     | {"{add}185{/add}"}
322921     | {"{add}185{/add}"}
322921     | {"{add}187{/add}"}
  1. 为数据采样创建索引哪个更好?
  2. 在“WHERE”中使用哪个表达式更好?

【问题讨论】:

  • 您应该查看全文索引或 GIN 索引。

标签: sql postgresql indexing


【解决方案1】:

最简单的解决方案就是构建一个pg_trgm index

 create extension pg_trgm;
 create index on product using gin (description gin_trgm_ops);

然后你可以使用相同的查询,只删除LOWER并将LIKE更改为ILIKE。

这应该已经足够好了,但如果不是,您可以创建一个更有针对性的索引。您需要创建一个辅助函数来进行聚合,因为您不能将聚合直接放入功能索引中。

create function extract_tokens(text) returns text[] immutable language sql as $$ 
   select array_agg(regexp_matches[1]) from 
      regexp_matches ($1, '\{add\}(\d+)\{\/add\}+','g') 
$$;

请注意,我将捕获括号移入,所以它们只得到数字而不是周围的标签,这看起来像是噪音。有比赛的事实证明他们在那里,我们不需要看到他们。

create index on product using gin (extract_tokens(description))

select * from product where extract_tokens(description) @> ARRAY['185'];

【讨论】:

  • 完美 > 时间:0,253s
【解决方案2】:

为了更好地搜索,您需要为“描述”列创建索引

当使用like时,记住只有这个通配符可以和索引一起使用

SELECT product_id, desciption FROM product WHERE LOWER(desciption) like '{add}185{/add}%'

所以您上面的查询不适用于索引

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2017-08-15
    • 2017-04-27
    • 1970-01-01
    • 2011-04-28
    相关资源
    最近更新 更多