Re: [HACKERS] JSONB - JSONB operator feature request - Mailing list pgsql-hackers

From David Fetter
Subject Re: [HACKERS] JSONB - JSONB operator feature request
Date
Msg-id 20170718174924.GH11340@fetter.org
Whole thread Raw
In response to [HACKERS] JSONB - JSONB operator feature request  (david.turon@linuxbox.cz)
Responses Re: [HACKERS] JSONB - JSONB operator feature request
List pgsql-hackers
On Tue, Jul 18, 2017 at 01:36:32PM +0200, david.turon@linuxbox.cz wrote:
> Hi,
> 
> some users and me used hstore - hstore for example storing only changed 
> rows in trigger like:
> 
> hsore(NEW) - hstore(OLD)
> 
> There isn't same operator/function in JSON/JSONB. We can only remove keys 
> from JSONB, but not equal key-value pairs. Is there any chance to have 
> same feature with JSON/JSONB in postgres core?

Here's one slightly modified from http://coussej.github.io/2016/05/24/A-Minus-Operator-For-PostgreSQLs-JSONB/

CREATE OR REPLACE FUNCTION jsonb_minus ( arg1 jsonb, arg2 jsonb )
RETURNS jsonb
LANGUAGE sql
AS $$
SELECT COALESCE(json_object_agg(       key,       CASE           -- if the value is an object and the value of the
secondargument is           -- not null, we do a recursion           WHEN jsonb_typeof(value) = 'object' AND arg2 ->
keyIS NOT NULL         THEN jsonb_minus(value, arg2 -> key)           -- for all the other types, we just return the
value          ELSE value       END   ), '{}')::jsonb
 
FROM jsonb_each(arg1)
WHERE arg1 -> key IS DISTINCT FROM arg2 -> key 
$$;

CREATE OPERATOR - (   PROCEDURE = jsonb_minus,   LEFTARG   = jsonb,   RIGHTARG  = jsonb
);

I suspect that there's a faster way to do the jsonb_minus function
internally.

Best,
David.
-- 
David Fetter <david(at)fetter(dot)org> http://fetter.org/
Phone: +1 415 235 3778  AIM: dfetter666  Yahoo!: dfetter
Skype: davidfetter      XMPP: david(dot)fetter(at)gmail(dot)com

Remember to vote!
Consider donating to Postgres: http://www.postgresql.org/about/donate



pgsql-hackers by date:

Previous
From: Mark Rofail
Date:
Subject: Re: [HACKERS] GSoC 2017: Foreign Key Arrays
Next
From: Mark Rofail
Date:
Subject: Re: [HACKERS] GSoC 2017: Foreign Key Arrays