PostgreSQL 函数式索引使用注意 - 暨非immutable函数不适合索引的原因

简介:

标签

PostgreSQL , 表达式 , 函数稳定性 , immutable


背景

PostgreSQL支持表达式索引,但是表达式必须是immutable的,也即是当输入参数不变时,结果是永恒不变的。

因为当表达式涉及的变量不变时,索引本身不会变化。

给个例子,如果我们有一张表存储了商品价格,另一张表存储了商品折扣 ,如果我们想通过折扣后的价格范围搜索符合价格区间的商品ID,可以使用索引吗?

表达式索引,可以。但是前提是:输入一个商品ID时,商品原价永恒不变。

否则原价发生变化就可能出现索引内容与实际不一致的问题。

例子

create extension btree_gist;  

商品表

create table t_item (id int8 primary key, price jsonb);  

折扣表

create table t_item_discount (id int8, ts daterange, country text, discount float4);  

获取商品折后价格的函数

create or replace function get_price(int8,text,float4) returns float8 as $$  
  select (price->>$2)::float8*$3 from t_item where id=$1;  
$$ language sql strict immutable;  

函数索引,immutable函数

create index idx_t_item_discount_1 on t_item_discount using gist (ts, country, get_price(id,country,discount));  

写入商品

insert into t_item values (1, jsonb '{"global":200, "china":150}');  

写入折扣

insert into t_item_discount values (1, daterange('2018-01-01', '2018-01-10'), 'global', 0.4);  

强制索引扫描

set enable_bitmapscan=off;  
set enable_seqscan=off;  
  
postgres=# explain select ctid,get_price(id,country,discount),* from t_item_discount where ts @> '2018-01-01'::date and get_price(id,country,discount)<300 and country='china';  
                                                                QUERY PLAN                                                                   
-------------------------------------------------------------------------------------------------------------------------------------------  
 Index Scan using idx_t_item_discount_1 on t_item_discount  (cost=0.12..8.40 rows=1 width=90)  
   Index Cond: ((ts @> '2018-01-01'::date) AND (country = 'china'::text) AND (get_price(id, country, discount) < '300'::double precision))  
(2 rows)  
  
postgres=# explain select ctid,get_price(id,country,discount),* from t_item_discount where ts @> '2018-01-01'::date and country='china' and get_price(id,country,discount)<300;  
                                                                QUERY PLAN                                                                   
-------------------------------------------------------------------------------------------------------------------------------------------  
 Index Scan using idx_t_item_discount_1 on t_item_discount  (cost=0.12..8.40 rows=1 width=90)  
   Index Cond: ((ts @> '2018-01-01'::date) AND (country = 'china'::text) AND (get_price(id, country, discount) < '300'::double precision))  
(2 rows)  
  
  
  
postgres=# select ctid,get_price(id,country,discount),* from t_item_discount where ts @> '2018-01-01'::date and country='global' and get_price(id,country,discount)<300;  
 ctid  |    get_price     | id |           ts            | country | discount   
-------+------------------+----+-------------------------+---------+----------  
 (0,1) | 80.0000011920929 |  1 | [2018-01-01,2018-01-10) | global  |      0.4  
(1 row)  

但是如果原价变化,索引并不会更新

postgres=# update t_item set price = jsonb '{"global":2000, "china":1500}' where id=1;  
UPDATE 1  

下面的结果显然是错误的

postgres=# select ctid,get_price(id,country,discount),* from t_item_discount where ts @> '2018-01-01'::date and country='global' and get_price(id,country,discount)<300;  
 ctid  |    get_price     | id |           ts            | country | discount   
-------+------------------+----+-------------------------+---------+----------  
 (0,1) | 800.000011920929 |  1 | [2018-01-01,2018-01-10) | global  |      0.4  
(1 row)  
postgres=# update t_item_discount set discount = discount where id=1;  
UPDATE 1  
postgres=# select ctid,get_price(id,country,discount),* from t_item_discount where ts @> '2018-01-01'::date and country='global' and get_price(id,country,discount)<300;  
 ctid  |    get_price     | id |           ts            | country | discount   
-------+------------------+----+-------------------------+---------+----------  
 (0,2) | 800.000011920929 |  1 | [2018-01-01,2018-01-10) | global  |      0.4  
(1 row)  

只有当表达式字段内容发生变化时,相应的表达式才会变化

postgres=# update t_item_discount set discount=discount+0.0000001 where id=1;  
UPDATE 1  
  
postgres=# select ctid,get_price(id,country,discount),* from t_item_discount where ts @> '2018-01-01'::date and country='global' and get_price(id,country,discount)<300;  
 ctid | get_price | id | ts | country | discount   
------+-----------+----+----+---------+----------  
(0 rows)  
  
postgres=# select float4send(discount),* from t_item_discount ;  
 float4send | id |           ts            | country | discount   
------------+----+-------------------------+---------+----------  
 \x3eccccd0 |  1 | [2018-01-01,2018-01-10) | global  |      0.4  
(1 row)  

参考

《PostgreSQL Oracle 兼容性之 - PL/SQL DETERMINISTIC 与PG函数稳定性(immutable, stable, volatile)》

《PostgreSQL 函数稳定性与constraint_excluded分区表逻辑推理过滤的CASE》

《函数稳定性讲解 - retalk PostgreSQL function's [ volatile|stable|immutable ]》

《函数稳定性讲解 - 函数索引思考, pay attention to function index used in PostgreSQL》

《函数稳定性讲解 - Thinking PostgreSQL Function's Volatility Categories》

相关实践学习
使用PolarDB和ECS搭建门户网站
本场景主要介绍如何基于PolarDB和ECS实现搭建门户网站。
阿里云数据库产品家族及特性
阿里云智能数据库产品团队一直致力于不断健全产品体系,提升产品性能,打磨产品功能,从而帮助客户实现更加极致的弹性能力、具备更强的扩展能力、并利用云设施进一步降低企业成本。以云原生+分布式为核心技术抓手,打造以自研的在线事务型(OLTP)数据库Polar DB和在线分析型(OLAP)数据库Analytic DB为代表的新一代企业级云原生数据库产品体系, 结合NoSQL数据库、数据库生态工具、云原生智能化数据库管控平台,为阿里巴巴经济体以及各个行业的企业客户和开发者提供从公共云到混合云再到私有云的完整解决方案,提供基于云基础设施进行数据从处理、到存储、再到计算与分析的一体化解决方案。本节课带你了解阿里云数据库产品家族及特性。
目录
相关文章
|
6月前
|
存储 监控 关系型数据库
B-tree不是万能药:PostgreSQL索引失效的7种高频场景与破解方案
在PostgreSQL优化实践中,B-tree索引虽承担了80%以上的查询加速任务,但因多种原因可能导致索引失效,引发性能骤降。本文深入剖析7种高频失效场景,包括隐式类型转换、函数包裹列、前导通配符等,并通过实战案例揭示问题本质,提供生产验证的解决方案。同时,总结索引使用决策矩阵与关键原则,助你让索引真正发挥作用。
432 0
|
监控 关系型数据库 数据库
PostgreSQL的索引优化策略?
【8月更文挑战第26天】PostgreSQL的索引优化策略?
498 1
|
10月前
|
SQL 关系型数据库 OLAP
云原生数据仓库AnalyticDB PostgreSQL同一个SQL可以实现向量索引、全文索引GIN、普通索引BTREE混合查询,简化业务实现逻辑、提升查询性能
本文档介绍了如何在AnalyticDB for PostgreSQL中创建表、向量索引及混合检索的实现步骤。主要内容包括:创建`articles`表并设置向量存储格式,创建ANN向量索引,为表增加`username`和`time`列,建立BTREE索引和GIN全文检索索引,并展示了查询结果。参考文档提供了详细的SQL语句和配置说明。
334 2
|
11月前
|
JSON 关系型数据库 PostgreSQL
PostgreSQL 9种索引的原理和应用场景
PostgreSQL 支持九种主要索引类型,包括 B-Tree、Hash、GiST、SP-GiST、GIN、BRIN、Bitmap、Partial 和 Unique 索引。每种索引适用于不同场景,如 B-Tree 适合范围查询和排序,Hash 仅用于等值查询,GiST 支持全文搜索和几何数据查询,GIN 适用于多值列和 JSON 数据,BRIN 适合非常大的表,Bitmap 适用于低基数列,Partial 只对部分数据创建索引,Unique 确保列值唯一。
|
关系型数据库 Serverless 定位技术
PostgreSQL GIS函数判断两条线有交点的函数是什么?
PostgreSQL GIS函数判断两条线有交点的函数是什么?
905 60
|
SQL 自然语言处理 关系型数据库
在 PostgreSQL 中使用 `REPLACE` 函数
【8月更文挑战第8天】
2129 9
在 PostgreSQL 中使用 `REPLACE` 函数
|
SQL 关系型数据库 C语言
PostgreSQL SQL扩展 ---- C语言函数(三)
可以用C(或者与C兼容,比如C++)语言编写用户自定义函数(User-defined functions)。这些函数被编译到动态可加载目标文件(也称为共享库)中并被守护进程加载到服务中。“C语言函数”与“内部函数”的区别就在于动态加载这个特性,二者的实际编码约定本质上是相同的(因此,标准的内部函数库为用户自定义C语言函数提供了丰富的示例代码)
|
关系型数据库 PostgreSQL
PostgreSQL的null值函数
【8月更文挑战第20天】PostgreSQL的null值函数
507 3
|
SQL Oracle 关系型数据库
|
关系型数据库 BI 数据处理

相关产品

  • 云原生数据库 PolarDB
  • 云数据库 RDS PostgreSQL 版
  • 推荐镜像

    更多