2016-11-18 43 views
-2

的Postgres 9.6.1如何獲取並比較Postgres中jsonb數組的元素?

 

    CREATE TABLE "public"."test" (
    "id" int4 NOT NULL, 
    "packet" jsonb, 
    ) 
    WITH (OIDS=FALSE) 
    ; 

Jsonb

 

    {"1": {"end": 14876555, "quantity":10}, "2": {"end": 14876555, "quantity":10} } 

 

    [{"op": 1, "end": 14876555, "quantity": 10}, {"op": 2, "end": 14876555, "quantity": 20}] 

所有嘗試檢索錯誤的陣列的結果: 不能從對象中提取元素

有必要進行比較所有元素「結束」< 1490000並找到該ID。

「OP」:1或「1」:變量值和完整路徑是不適合的解決方案

+2

https://www.postgresql.org/docs/current/static/functions-json.html – SeinopSys

+0

顯示更好的例子。也許,如果我沒有嘗試過各種選擇,那麼在這裏我不會寫。例如:從json_array_elements('[{「op」:3,「end」:14876555,「quantity」:10},{「op」:4,「end」:14876556,「數量「:10}]')as packet where(packet - >>'end'):: int> 14876555這可以工作,但是如果數據表9.6.1不起作用。 –

回答

0

如果沒有約定的JSON結構的最佳解決方案IMO是一樣的東西

select * 
from 
    public.test, 
    regexp_matches(packet::text, '"end":\s*(\d+)', 'g') as e(x) 
where 
    x[1]::numeric < 1490000; 
+0

感謝您的回覆。不幸的是,一些表格可能會顯着增長搜索json不是很快,regexp會更慢。我並沒有認爲這是一個動態路徑的問題。早期版本的示例我沒有獲得,因此我要求查看一個有效的示例。 –

+0

@NestorUzhvij你問:'select x,y,'{「a」:[「b」,「c」]}':: jsonb-> x-> y from(values('a',0 ))作爲t(x,y);'?但是請閱讀:[PostgreSQL反模式:不必要的json/hstore動態列](http://blog.2ndquadrant.com/postgresql-anti-patterns-unnecessary-jsonhstore-dynamic-columns/) – Abelisto

+0

謝謝。文章幫助:) –