Postgres 9.5
我的表格中有一列jsonb;
CREATE TABLE public.test
(
objectstate jsonb
)
及其上的索引:
CREATE INDEX "test.type"
ON public.test
USING btree
((objectstate ->> 'type'::text) COLLATE pg_catalog."default");
我还有返回依赖类型的函数....它更复杂,所以我给出一个例子....
CREATE OR REPLACE FUNCTION testfunc(sxtype text)
RETURNS text AS
$BODY$
BEGIN
return '{type1, type2}';
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
现在我得到了什么:
select testfunc('type1')
给了我'{type1, type2}'
下一个语法效果很好,DOES使用索引:
select * from test where objectstate->>'type' = ANY('{type1, type2}'::text[])
但是一旦我尝试将它们组合起来,就不使用索引
select * from test
where objectstate->>'type' = ANY((select testfunc('type1'))::text[])
奇怪的是下一个查询再次使用sytax! (但我无法在任何地方使用此解决方法)
select * from test
where objectstate->>'type' = ANY((select testfunc('type1'))::text[])
order by objectstate->>'type'
解释分析给了我:
"Seq Scan on test (cost=0.26..530872.27 rows=2238634 width=743) (actual time=1107.155..7992.825 rows=129 loops=1)"
" Filter: ((test ->> 'type'::text) = ANY (($0)::text[]))"
" Rows Removed by Filter: 4063727"
" InitPlan 1 (returns $0)"
" -> Result (cost=0.00..0.26 rows=1 width=0) (actual time=0.718..0.718 rows=1 loops=1)"
"Planning time: 0.319 ms"
"Execution time: 7992.870 ms"
当订单适用时:
"Index Scan using "test.type" on test (cost=0.70..545058.44 rows=2238634 width=743) (actual time=0.645..0.740 rows=129 loops=1)"
" Index Cond: ((objectstate ->> 'type'::text) = ANY (($0)::text[]))"
" InitPlan 1 (returns $0)"
" -> Result (cost=0.00..0.26 rows=1 width=0) (actual time=0.617..0.617 rows=1 loops=1)"
"Planning time: 0.300 ms"
"Execution time: 0.782 ms"
任何想法如何强制postgres使用索引而不应用订单?
答案 0 :(得分:1)
可能不是答案,但似乎您可以使用
将功能定义从VOLATILE
更改为IMMUTABLE
CREATE OR REPLACE FUNCTION testfunc(sxtype text)
RETURNS text AS
$BODY$
BEGIN
return '{type1, type2}';
END;
$BODY$
LANGUAGE plpgsql IMMUTABLE
COST 100;
使用VOLATILE函数Postgres不会应用优化,因为VOLATILE函数可能会更改数据,并且函数的结果是不可预测的。更多文档https://www.postgresql.org/docs/9.5/static/sql-createfunction.html