How to get only the jsonb of specific keys from postgres?

后端 未结 5 539
忘掉有多难
忘掉有多难 2021-02-06 01:10

I\'m aware that you can remove keys from a jsonb in postgres using something like this

select \'{\"a\": 1, \"b\": 2, \"c\":3}\'::jsonb -\'a\';
 ?column?
--------         


        
5条回答
  •  耶瑟儿~
    2021-02-06 01:32

    If you want to filter multiple rows with JSONB documents in each of them:

    -- Let's generate rows with JSONB column:
    WITH s AS (SELECT generate_series(1, 100) num),
    g AS (SELECT num, jsonb_build_object('a', s.num, 'b', s.num * 2) obj FROM s),
    
    -- A "filter" adding (in my example only keys of "filter" document remain in result rows)
    j AS (SELECT '{"a": "int", "c": "string"}'::jsonb AS filter),
    a AS (SELECT (ARRAY(SELECT jsonb_object_keys(filter))) AS ar FROM j),
    
    -- Useless keys removing
    o AS (SELECT jsonb_object_agg(l.key, l.value) obj
            FROM g, LATERAL jsonb_each(g.obj) l, a 
            WHERE l.key = ANY(a.ar)
            GROUP BY num)
    
    SELECT * FROM o ORDER BY obj->'a';
    

提交回复
热议问题