为了运行查询,
SELECT count(*) FROM reservations WHERE
(((json #>> '{details, attributes, checkIn}')::timestamptz at time zone (json #>> '{details, attributes, destinationTimeZone}'))) >= '2019-01-17' AND (((json #>> '{details, attributes, checkIn}')::timestamptz at time zone (json #>> '{details, attributes, destinationTimeZone}'))) < '2020-04-01';
我创建了功能索引:
CREATE FUNCTION text2tstz(text) RETURNS timestamp with time zone
LANGUAGE sql IMMUTABLE AS
$$SELECT CASE WHEN $1 ~ '^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z?$'
THEN CAST($1 AS timestamp with time zone)
END$$;
CREATE INDEX CONCURRENTLY checkIn_index ON reservations
((text2tstz(json ->> '{details,attributes,checkIn}')at time zone (json ->> '{details, attributes, destinationTimeZone}')));
索引已成功创建,但是当我进行 EXPLAIN ANALYZE 时,我没有发现我的索引正在被使用,任何人都可以帮助我解决我的错误吗?
explain analyze SELECT count(*) FROM reservations WHERE
((text2tstz(json #>> '{details, attributes, checkIn}') at time zone (json #>> '{details, attributes, destinationTimeZone}'))) >= '2019-01-17' AND ((text2tstz(json #>> '{details, attributes, checkIn}') at time zone (json #>> '{details, attributes, destinationTimeZone}'))) < '2020-04-01';
解释分析结果
Aggregate (cost=120515.80..120515.81 rows=1 width=0) (actual time=13794.176..13794.176 rows=1 loops=1)
-> Seq Scan on reservations (cost=0.00..120510.32 rows=2193 width=0) (actual time=9479.960..13792.877 rows=2973 loops=1)
Filter: ((timezone((json #>> '{details,attributes,destinationTimeZone}'::text[]), ((json #>> '{details,attributes,checkIn}'::text[]))::timestamp with time zone) >= '2019-01-17 00:00:00'::timestamp without time zone) AND (timezone((json #>> '{details,attributes,destinationTimeZone}'::text[]), ((json #>> '{details,attributes,checkIn}'::text[]))::timestamp with time zone) < '2020-04-01 00:00:00'::timestamp without time zone))
Rows Removed by Filter: 435536
Planning time: 0.246 ms
Execution time: 13794.257 ms
我正在使用 Postgresql 9.4.8