在 PostgreSQL 9.3 中,有多种方法可以构建一个表达式,它指向一个 json 字段的嵌套属性:
data->'foo'->>'bar'
data#>>'{foo,bar}'
json_extract_path_text(data, 'foo', 'bar')
因此,如果查询的表达式与索引的表达式完全匹配,PostgreSQL 只使用这些索引。
CREATE TABLE json_test_index1(data json);
CREATE TABLE json_test_index2(data json);
CREATE TABLE json_test_index3(data json);
CREATE INDEX ON json_test_index1((data->'foo'->>'bar'));
CREATE INDEX ON json_test_index2((data#>>'{foo,bar}'));
CREATE INDEX ON json_test_index3((json_extract_path_text(data, 'foo', 'bar')));
-- these queries use an index, while all other combinations not:
EXPLAIN SELECT * FROM json_test_index1 WHERE data->'foo'->>'bar' = 'baz';
EXPLAIN SELECT * FROM json_test_index2 WHERE data#>>'{foo,bar}' = 'baz';
EXPLAIN SELECT * FROM json_test_index3 WHERE json_extract_path_text(data, 'foo', 'bar') = 'baz';
我的问题是:
这种行为是有意的吗?我认为查询优化器应该(至少)将索引与#>>
运算符一起使用,当查询包含适当的调用时json_extract_path_text()
-- 反之亦然。
如果我想在我的应用程序中使用更多这些表达式(不仅仅是一个,f.ex。坚持使用->
&->>
运算符),我应该构建哪些索引?(我希望,不是全部。)
有没有机会,一些未来的 Postgres 版本的优化器会理解这些表达式的等价性?
编辑:
当我为此创建一个额外的运算符时:
CREATE OPERATOR ===> (
PROCEDURE = json_extract_path_text,
LEFTARG = json,
RIGHTARG = text[]
);
此查询(上一个示例中的表)仍然不使用它的索引:
EXPLAIN SELECT * FROM json_test_index3 WHERE data ===> '{foo,bar}' = 'baz';
奖金问题:
虽然 Postgres 将运算符扩展为函数调用(在幕后),但为什么仍然不使用它的索引?