What’s the proper index for querying structures in arrays in Postgres jsonb?

First of all, you cannot access JSON array values like that. For a given json value: [{“event_slug”:”test_1″,”start_time”:”2014-10-08″,”end_time”:”2014-10-12″}, {“event_slug”:”test_2″,”start_time”:”2013-06-24″,”end_time”:”2013-07-02″}, {“event_slug”:”test_3″,”start_time”:”2014-03-26″,”end_time”:”2014-03-30″}] A valid test against the first array element would be: WHERE e->0->>’event_slug’ = ‘test_1′ But you probably don’t want to limit your search to the first element of the array. With the jsonb data type in … Read more

Flatten aggregated key/value pairs from a JSONB field?

This particular case The function below dynamically creates a view based on a table: create or replace function create_totals_view(table_name text) returns void language plpgsql as $$ declare s text; begin execute format ($fmt$ select string_agg(format(‘star_pu->>”%s” “%s”‘, key, key), ‘,’) from ( select distinct key from %s, json_each(star_pu) order by 1 ) s; $fmt$, ‘%s’, ‘%s’, … Read more

How to perform update operations on columns of type JSONB in Postgres 9.4

If you’re able to upgrade to Postgresql 9.5, the jsonb_set command is available, as others have mentioned. In each of the following SQL statements, I’ve omitted the where clause for brevity; obviously, you’d want to add that back. Update name: UPDATE test SET data = jsonb_set(data, ‘{name}’, ‘”my-other-name”‘); Replace the tags (as oppose to adding … Read more

Query for array elements inside JSON type

jsonb in Postgres 9.4+ You can use the same query as below, just with jsonb_array_elements(). But rather use the jsonb “contains” operator @> in combination with a matching GIN index on the expression data->’objects’: CREATE INDEX reports_data_gin_idx ON reports USING gin ((data->’objects’) jsonb_path_ops); SELECT * FROM reports WHERE data->’objects’ @> ‘[{“src”:”foo.png”}]’; Since the key objects … Read more