2015-09-23 158 views
0

我有一個jsonb存儲我的訂單產品:JSONB的Postgres 9.4

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. 所有的銷售選擇具有的itemid如P%1
  3. 選擇具有所有銷售的所有銷售數量> 10
  4. 讓每個產品總數量

回答

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; 
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。僅適用於「配置」表所需的行。