Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
Postgres accessing JSONB elements in efficient way

I have batch_table table, which contain batchid type of serial int and data type of JSONB, I indexed data column using GIN,

batchid | data
---------------------------------------------
1  | [{"year":2000,"productid":[21, 32, 5]}]
2  | [{"year":2001,"productid":[21, 39, 5]},{"year":2000,"productid":[1, 25, 5]}]
3  | NULL
4. | [{"year": 2000,"productid":[5]}

Now I want to get batchid by using following requirements
1. year = 2000 & productid= 5
2. year = 2000 & productid= (21 or 5)
3. year = 2000 & productid= (21 & 5)

and I tried this

SELECT batchid FROM batch_table WHERE (data->>'year')::int = 2000 AND (data->>'productid')::int = 5;

with AND & OR for other queries

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can use the containment operator @> to search in jsonb (this can even use your index):

1.

select *
from   batch_table
where  data @> '[{"year":2000,"productid":[5]}]';

2.

select *
from   batch_table
where  data @> '[{"year":2000,"productid":[21]}]'
or     data @> '[{"year":2000,"productid":[5]}]';

3.

Depending on your needs, you can use one of these:

  • These will select rows, where year=2000 with productid=21 are in the same object and year=2000 with productid=5 are in the same object (but these objects can be different ones).

    select *
    from   batch_table
    where  data @> '[{"year":2000,"productid":[21]}]'
    and    data @> '[{"year":2000,"productid":[5]}]';
    
    select *
    from   batch_table
    where  data @> '[{"year":2000,"productid":[21]},{"year":2000,"productid":[5]}]';
    
  • This will select rows, where year=2000 with productid=21 are in the same object as well as productid=5

    select *
    from   batch_table
    where  data @> '[{"year":2000,"productid":[21, 5]}]';
    

http://rextester.com/ZMCUME18642

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda