0
CREATE TABLE company (id SERIAL, companyJson JSONB);
CREATE INDEX comapny_gin_idx ON company USING gin (companyJson);

INSERT INTO company (id, companyJson) 
  VALUES (1, '[{"name": "t", "company": "company1"}]');

INSERT INTO company (id, companyJson) 
  VALUES (2, '[{"name": "b", "company":"company2"}, {"name": "b", "company":"company3"}]');


 SELECT * FROM company WHERE companyJson @> '[{"company": "company2" , "name": "b"}]';

The output of the above program is

2   [{"name": "b", "company": "company2"}, {"name": "b", "company": "company3"}]

Is there anyway to return {"name": "b", "company": "company2"} instead whole row.

  • version is PostgreSQL 11.5 – Balu 17 hours ago
0

I can only think of unnesting the array and the return the element from that:

SELECT x.j
FROM company c
  cross join jsonb_array_elements(c.companyjson) as x(j)
where x.j = '{"company": "company2" , "name": "b"}'
  • Does this uses indexing which i have created on the table. Since one record may contain 5000 array of json objects. – Balu 17 hours ago
  • @Balu: no I don't think so, but you can see for yourself by using explain (analyze) select .. – a_horse_with_no_name 17 hours ago
0

You can directly return the first component through companyJson -> 0 which contains -> operand returning the first component by argument zero :

 SELECT companyJson -> 0 as companyJson
   FROM company 
  WHERE companyJson @> '[{"company": "company2" , "name": "b"}]';

Demo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.