Postgresql 9.5 jsonb - 搜索数组中的日期范围

时间:2017-05-12 19:32:23

标签: postgresql

我有一个名为 orders 的表,它有一个名为 lineItems 的jsonb列,其中包含一行数组,每行都有一个名为 closedDate 。我想搜索订单表并返回包含指定日期范围内的行的所有记录。

[
   {productName:"shirt", price: 2.99, closedDate:1494607506041},
   {productName:"pants", price: 3.99, closedDate:1494607506041}
]

2 个答案:

答案 0 :(得分:0)

try jsonb_array_elements - 这是示例:

t=# with b as (
  with j as (
    select
      'data'::text some_column
     ,'[
   {"productName":"shirt", "price": 2.99, "closedDate":1494607506041},
   {"productName":"pants", "price": 3.99, "closedDate":1494607506041}
]'::jsonb v
    )
  select (jsonb_array_elements(j.v)->>'closedDate')::bigint cmp,*
  from j
)
select distinct some_column,v
from b
where cmp > 1494607506040 and cmp < 1494607506042;
 some_column |                                                                      v
-------------+----------------------------------------------------------------------------------------------------------------------------------------------
 data        | [{"price": 2.99, "closedDate": 1494607506041, "productName": "shirt"}, {"price": 3.99, "closedDate": 1494607506041, "productName": "pants"}]
(1 row)

如果任何数组closedDate进入区间cmp > 1494607506040 and cmp < 1494607506042

,则上面将获得该行

答案 1 :(得分:0)

with orders (lineItens) as ( values ('
    [
       {"productName":"shirt", "price": 2.99, "closedDate":1494607506041},
       {"productName":"pants", "price": 3.99, "closedDate":1494607505041}
    ]'::jsonb
))
select lineItens
from orders
where exists (
    select 1
    from jsonb_array_elements(lineItens) e(e)
    where (e ->> 'closedDate')::bigint between 1494607506040 and 1494607506045
)
;
                                                                  lineitens                                                                   
----------------------------------------------------------------------------------------------------------------------------------------------
 [{"price": 2.99, "closedDate": 1494607506041, "productName": "shirt"}, {"price": 3.99, "closedDate": 1494607505041, "productName": "pants"}]