为未使用的 PostgreSQL jsonb 列创建的索引
Index created for PostgreSQL jsonb column not utilized
我已经为 jsonb 列中的字段创建了一个索引:
create index on Employee using gin ((properties -> 'hobbies'))
生成的查询是:
CREATE INDEX employee_expr_idx ON public.employee USING gin (((properties -> 'hobbies'::text)))
我的搜索查询结构如下:
SELECT * FROM Employee e
WHERE e.properties @> '{"hobbies": ["trekking"]}'
AND e.department = 'Finance'
运行 此查询的 EXPLAIN 命令给出:
Seq Scan on employee e (cost=0.00..4452.94 rows=6 width=1183)
Filter: ((properties @> '{"hobbies": ["trekking"]}'::jsonb) AND (department = 'Finance'::text))
据此,我不确定索引是否用于搜索。
整个设置可以吗?
您在 WHERE 子句中使用的表达式必须 完全匹配索引中的表达式,您的索引使用表达式:((properties -> 'hobbies'::text))
但您的查询仅使用 e.properties
在左边。
要使用该索引,您的 WHERE 子句需要使用与索引中相同的表达式:
SELECT *
FROM Employee e
WHERE (properties -> 'hobbies') @> '["trekking"]'
AND e.department = 'Finance'
但是:您的执行计划显示 table 员工非常小(行数=6)。 table 这么小,无论您定义何种索引,Seq Scan 始终是检索数据的最快方式。
我已经为 jsonb 列中的字段创建了一个索引:
create index on Employee using gin ((properties -> 'hobbies'))
生成的查询是:
CREATE INDEX employee_expr_idx ON public.employee USING gin (((properties -> 'hobbies'::text)))
我的搜索查询结构如下:
SELECT * FROM Employee e
WHERE e.properties @> '{"hobbies": ["trekking"]}'
AND e.department = 'Finance'
运行 此查询的 EXPLAIN 命令给出:
Seq Scan on employee e (cost=0.00..4452.94 rows=6 width=1183)
Filter: ((properties @> '{"hobbies": ["trekking"]}'::jsonb) AND (department = 'Finance'::text))
据此,我不确定索引是否用于搜索。
整个设置可以吗?
您在 WHERE 子句中使用的表达式必须 完全匹配索引中的表达式,您的索引使用表达式:((properties -> 'hobbies'::text))
但您的查询仅使用 e.properties
在左边。
要使用该索引,您的 WHERE 子句需要使用与索引中相同的表达式:
SELECT *
FROM Employee e
WHERE (properties -> 'hobbies') @> '["trekking"]'
AND e.department = 'Finance'
但是:您的执行计划显示 table 员工非常小(行数=6)。 table 这么小,无论您定义何种索引,Seq Scan 始终是检索数据的最快方式。