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

问题描述 投票:6回答:1

我目前正在学习新的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'))

以某种方式,当我运行解释分析时,我没有看到使用该索引:

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.
indexing jsonb postgresql-9.4
1个回答
0
投票

我正面临着同样的问题,有人知道答案吗?

© www.soinside.com 2019 - 2024. All rights reserved.