Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres jsonb 'NOT contains' operator

Tags:

I'm experimenting with postgres jsonb column types, and so far so good. One common query I'm using is like this:

select count(*) from jsonbtest WHERE attributes @> '{"City":"Mesa"}'; 

How do I reverse that? Is there a different operator or is it simply used as

select count(*) from jsonbtest WHERE NOT attributes @> '{"City":"Mesa"}'; 
like image 319
user101289 Avatar asked Sep 28 '16 00:09

user101289


People also ask

How do I query Jsonb data in PostgreSQL?

Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.

What is Jsonb in Postgres?

JSONB stands for “JSON Binary” or “JSON better” depending on whom you ask. It is a decomposed binary format to store JSON. JSONB supports indexing the JSON data, and is very efficient at parsing and querying the JSON data. In most cases, when you work with JSON in PostgreSQL, you should be using JSONB.

Should I use JSON or Jsonb Postgres?

If duplicate keys are specified in the input, only the last value is kept. In general, most applications should prefer to store JSON data as jsonb , unless there are quite specialized needs, such as legacy assumptions about ordering of object keys. RFC 7159 specifies that JSON strings should be encoded in UTF8.


Video Answer


1 Answers

Two way, you can test any json(b) value

  • the ->> operator extract value as text. But this operation slow, if you will use the value only test
  • the @> operator test any json(b) contain any json(b). This is a quick but you are not tested NOT option.

Simply and quick way:

NOT (attribute @> '{"City":"Mesa"}'::jsonb) 

I've change attribute->>'City' <> 'Mesa' to NOT (attribute @> '{"City":"Mesa"}'::jsonb) and my ~2.000.000 rows query result time changed 45secs to 25secs.

like image 57
Ahmet Erkan ÇELİK Avatar answered Sep 22 '22 04:09

Ahmet Erkan ÇELİK