PostgreSQL中JSON的索引

    由于JSON类型上没有提供比较函数,所以只能在JSON类型的列上建立函数索引,不能直接建索引。

1.建表

create table test(
  id int,
  doc json
);

2.建函数索引

  (1) 函数定义

create or replace function rand_string(integer)
returns text as
$body$
 select array_to_string(
    ARRAY( select substring('qwertyuiopasdfghjklzxcvbnm' FROM(ceil(random()*62))::int FOR 1) FROM generate_series(1,$1)),
    '')
 $body$
 LANGUAGE sql VOLATILE;   

   (2) 函数索引

create index on test using btree (json_extract_path_text(doc,'company'));

3.插入数据

 insert into test select t.seq,('{"info":{"name":"April","address":"Chengdu"},"company":"'||rand_string(10)||'"}')::json FROM
generate_series(1,10000) as t(seq);

4.执行计划

     先看一下没有走索引的执行计划

explain analyze verbose select * from test where doc->>'company'='gdz';

     再看一下走索引的执行计划

explain analyze verbose select * from test where json_extract_path_text(doc,'company')='gdz';

    由上图可知,没有走索引花费了6.472ms,走索引花费了0.058ms,相差111.5倍。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值