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.

1
  • version is PostgreSQL 11.5 Commented Feb 13, 2020 at 14:54

2 Answers 2

1

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"}'
Sign up to request clarification or add additional context in comments.

2 Comments

Does this uses indexing which i have created on the table. Since one record may contain 5000 array of json objects.
@Balu: no I don't think so, but you can see for yourself by using explain (analyze) select ..
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.