Postgres JSON equivalent to HSTORE subtract operator

1.6k Views Asked by At

Postgres' hstore extension has a neat subtraction operator:

hstore - text[]

hstore - hstore

In the first case, it removes the key/value pairs where the keys are found in the array of strings: in the second case it removes all matching key/value pairs from the first hstore that appear in the second hstore.

It seems this operator does not exist for the new jsonb data type. Is there a simple way to perform these tasks?

2

There are 2 best solutions below

3
On BEST ANSWER

The key is the json_each() function, and the ability in PostgreSQL to manually build up a json value.

Here is a function which can handle json - text[]:

CREATE OR REPLACE FUNCTION "json_object_delete_keys"(
  "json" json,
  VARIADIC "keys_to_delete" TEXT[]
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT COALESCE(
  (SELECT ('{' || string_agg(to_json("key") || ':' || "value", ',') || '}')
     FROM json_each("json")
    WHERE "key" <> ALL ("keys_to_delete")),
  '{}'
)::json
$function$;

To handle the json - json case, you simple need to change the WHERE clause:

    WHERE "json"->>"key" <> ("remove"->>"key")),
2
On

Accepted answer is great, but would be improved for the json - json case by checking for null as well:

WHERE NOT null_as_value_cmp((this_j->>"key"), (that_j->>"key"))

Without the NULL check you get {} instead of {"a":1}:

# select json_subtract('{"a":1, "b":2}'::json, '{"b":2}'::json);
 json_subtract
---------------
 {}
(1 row)

null_as_value_cmp is something like this and gets around JsNull being represented as the database NULL

CREATE OR REPLACE FUNCTION null_as_value_cmp(
    a text,
    b text
)
  RETURNS boolean
  LANGUAGE sql
  IMMUTABLE
  CALLED ON NULL INPUT
AS $function$
    SELECT CASE
        WHEN a IS NULL AND b IS NULL THEN
            TRUE
        WHEN (a IS NULL AND b IS NOT NULL) THEN
            FALSE
        WHEN (a IS NOT NULL AND b IS NULL) THEN
            FALSE
        WHEN a = b THEN
            TRUE
        ELSE
            FALSE
    END;
$function$;

[I don't have enough reputation to comment; not sure on the SO protocol here.]