JSONB Postgres 9.4

时间:2015-09-23 00:16:31

标签: search indexing postgresql-9.4 jsonb

我有一个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. 选择所有具有PROD001
  2. 的销售
  3. 选择所有具有itemid LIKE P%1
  4. 的销售
  5. 选择所有具有数量>的销售额10
  6. 获得每个产品总数量

2 个答案:

答案 0 :(得分:0)

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 :(得分:0)

示例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。仅适用于所需的行"配置"表