如何正确索引ORDER BY中使用的JSONB嵌套字段?

时间:2015-02-13 03:33:21

标签: indexing jsonb postgresql-9.4

我目前正在学习新的JSONB类型以及索引它的正确方法。我有一个jsonb details列,它存储类似于此的JSON:

{ 
  price: { amount: 435, currency: "USD" },
  condition: "Used", 
  make: "iPhone 5c", 
  serial: 203980982377442 
}

我的应用运行按price->amount键排序的选择查询,例如... order by details->'price'->'amount' desc nulls last。我的理解是否正确,为了使PostgreSQL 9.4能够利用索引,需要将其创建为order by字段?含义:

create index on ads using gin ((details -> 'price' -> 'amount'))

不知何故,当我运行explain analyze时,我没有看到使用这个索引:

dev=#  explain analyze 
select "ads"."id", "ads"."title", details->'price' as price from "ads" 
where ("classified_id" in 
  (select "id" from "classifieds" 
     where "id" = 1 or "parent_id" = 1 and "parent_id" is not null) 
     and "section_id" = 1) 
and "status_id" = 1 order by details->'price'->'amount' desc nulls last;

QUERY PLAN                                                                            
-------------------------
 Sort  (cost=20.30..20.31 rows=1 width=556) (actual time=0.276..0.277 rows=24 loops=1)
   Sort Key: (((ads.details -> 'price'::text) -> 'amount'::text))
   Sort Method: quicksort  Memory: 28kB
   ->  Nested Loop  (cost=0.14..20.29 rows=1 width=556) (actual time=0.042..0.227 rows=24 loops=1)
         Join Filter: (ads.classified_id = classifieds.id)
         Rows Removed by Join Filter: 144
         ->  Index Scan using ads_classified_id_section_id_category_id_idx on ads  (cost=0.14..8.16 rows=1 width=560) (actual time=0.018..0.028 rows=24 loops=1)
               Index Cond: (section_id = 1)
         ->  Seq Scan on classifieds  (cost=0.00..12.10 rows=2 width=4) (actual time=0.001..0.005 rows=7 loops=24)
               Filter: ((id = 1) OR ((parent_id = 1) AND (parent_id IS NOT NULL)))
               Rows Removed by Filter: 7
 Planning time: 0.760 ms
 Execution time: 6.

0 个答案:

没有答案