JSONB Postgres 9.4

JSONB Postgres 9.4

我有一个 jsonb 存储我的订单产品:

CREATE TABLE configuration (
  documentid text PRIMARY KEY
, data jsonb NOT NULL
);

记录:

(1, [{"itemid": "PROD001", "qty": 10}, {"itemid": "PROD002", "qty": 20}]),
(2, [{"itemid": "PROD001", "qty": 5}, {"itemid": "PROD003", "qty": 6}, {"itemid": "PROD004", "qty": 7}]),
(2, [{"itemid": "PROD002", "qty": 8}])

我已经使用 GIN 索引了数据。

我如何:

  1. Select 具有 PROD001 的所有销售额
  2. Select itemid 为 LIKE P%1 的所有销售
  3. Select 数量 > 10 的所有销售
  4. 获取每个产品的总数量

Postgres documentation regarding JSON功能非常清晰,值得您关注。至于您提供的用例,答案可能如下:

-- Answer 1
SELECT sales_item 
FROM configuration,jsonb_array_elements(data) AS sales_item
WHERE sales_item->>'itemid' = 'PROD001'; --  "->>" returns TEXT value
-- Answer 2
SELECT sales_item FROM configuration,jsonb_array_elements(data) AS sales_item
WHERE sales_item->>'itemid' LIKE 'P%1'; -- just use LIKE
-- Answer 3
SELECT sales_item FROM configuration,jsonb_array_elements(data) AS sales_item
WHERE (sales_item->>'qty')::INTEGER > 10; -- convert TEXT to INTEGER

对于最后一个例子,你只需要使用 Postgres Window function:

-- Answer 4 
SELECT DISTINCT documentid,sum((sales_item->>'qty')::INTEGER) 
OVER (PARTITION BY documentid)
FROM configuration,jsonb_array_elements(data) as sales_item;

示例 1,3 JsQuery extension

SELECT * FROM 
    (SELECT jsonb_array_elements(data) as elem FROM configuration
    WHERE data @@ '#.itemid = "PROD001"') q
    WHERE q.elem @@ 'itemid = "PROD001"'

SELECT * FROM 
    (SELECT jsonb_array_elements(data) as elem FROM configuration
    WHERE data @@ '#.qty > 10') q
    WHERE q.elem @@ 'qty > 10'

内部查询 WHERE 子句筛选行没有任何符合要求的数组元素。比 jsonb_array_elements func。仅适用于 "configuration" table.

的所需行