PG索引失效/生效分析
索引失效場景
1、任何計算、函數、類型轉換 2、!=、<> 3、IS NULL或者IS NOT NULL。類似導致索引失效的還有NOT IN,NOT LIKE等,但是NOT EXISTS不會導致索引失效。 4、模糊查詢通配符在開頭 5、索引字段在表中占比較高 6、多字段btree索引查詢條件不包含第一列 7、在WHERE中使用OR時,有一個列沒有索引,那么其它列的索引將不起作用 8、多字段索引查詢條件使用OR 在索引列上進行大於大於這類的比較后,這個列的索引是有效的,但是其后的索引將失效
jsonb字段索引分析(json支持GIN索引結構)
1.索引創建jsonb_ops操作符
-- ----------------------------
-- Indexes structure for table tb_security_event
-- ----------------------------
CREATE INDEX "notification_index" ON "public"."tb_security_event" USING gin (
"notification" "pg_catalog"."jsonb_ops"
);
索引分析執行SQL:
explain analyze verbose SELECT
securityev0_.ID AS id1_35_,
securityev0_.application AS applicat2_35_,
securityev0_.asset AS asset3_35_,
securityev0_.cia_level AS cia_leve4_35_,
securityev0_.component AS componen5_35_,
securityev0_.correlation_info AS correlat6_35_,
securityev0_.device_ip AS device_i7_35_,
securityev0_.event_change AS event_ch8_35_,
securityev0_.event_id AS event_id9_35_,
securityev0_.event_type AS event_t10_35_,
securityev0_.extra_fields AS extra_f11_35_,
securityev0_.insert_time AS insert_12_35_,
securityev0_.logs AS logs13_35_,
securityev0_.NAME AS name14_35_,
securityev0_.notification AS notific15_35_,
securityev0_.remarks AS remarks16_35_,
securityev0_.sensor_id AS sensor_17_35_,
securityev0_.siem_time AS siem_ti18_35_,
securityev0_.status AS status19_35_,
securityev0_.traffic AS traffic20_35_,
securityev0_.update_time AS update_21_35_
FROM
tb_security_event securityev0_
WHERE
securityev0_.notification @> '{"status":"gdz"}';
ORDER BY
securityev0_.insert_time DESC
LIMIT 5
注意點:
jsonb上的GIN索引支持“@>” “?” “?&” “?|”操作符
2.索引失效場景
當前表有索引,但是表數據為空 或者 表中只有少量數據 不走jsonb字段索引。
SQL執行結果(未使用索引):
3.索引生效場景
當表數據量多的情況下, jsonb字段索引生效。
SQL執行結果:(使用索引)