Soy nuevo en Postgres. Quiero eliminar el objeto JSON de la matriz JSON.
Tengo una tabla en la que estoy usando la columna jsonb en la que estoy almacenando una matriz JSON como se muestra a continuación.
[ { "id": "c75e7a-001e-4d64-9613-62f666d42103", "name": "Product1" }, { "id": "c75e7a-001e-4d64-9613-62f666d42103", "name": null }, { "id": "c75e7a-001e-4d64-9613-62f666d42103", "name": "Product2" }, { "id": "c75e7a-001e-4d64-9613-62f666d42103", "name": null } ]Quiero eliminar objetos JSON de una matriz que contiene un valor nulo en la clave de nombre.
después de eliminar la respuesta debería ser así
[ { "id": "c75e7a-001e-4d64-9613-62f666d42103", "name": "Product1" }, { "id": "c75e7a-001e-4d64-9613-62f666d42103", "name": "Product2" } ]alguien, por favor ayúdame a escribir la consulta SQL,
Sé cómo obtener todos los registros de la tabla que contiene el valor nulo.
SELECT * FROM table_name WHERE jsonb_col_name @>CAST('[{"name": null}]' AS JSONB);Pero no sé cómo hacer una consulta de eliminación, por favor ayúdenme con esto. ¿Cómo puedo hacerlo usando una consulta?
Desanime la matriz con jsonb_array_elements , excluya los valores null con un FILTER y agréguelos nuevamente, por ejemplo
SELECT jsonb_agg(j) FILTER (WHERE j->>'name' IS NOT NULL) FROM table_name t, jsonb_array_elements(jsonb_col) j GROUP BY t.jsonb_col; Demostración: db<>fiddle
Puede filtrar por j.value ->> 'name' IS NOT NULL después de dividir la matriz en subobjetos usando JSONB_ARRAY_ELEMENTS y luego aplicar JSONB_AGG para convertirlo nuevamente en una matriz como
SELECT JSONB_PRETTY( JSONB_AGG(j) ) FROM t, JSONB_ARRAY_ELEMENTS(json_data) AS j WHERE j.value ->> 'name' IS NOT NULL GROUP BY json_dataSi es necesario actualizar los datos existentes, entonces podría considerar usar
WITH tt AS ( SELECT JSONB_AGG(j) AS new_val, json_data FROM t, JSONB_ARRAY_ELEMENTS(json_data) AS j WHERE j.value ->> 'name' IS NOT NULL GROUP BY json_data ) UPDATE t SET json_data = new_val::JSONB FROM tt WHERE t.json_data = tt.json_dataPuedes usar json_array_elements :
select json_agg(i.value) from json_array_elements('[{"id": "c75e7a-001e-4d64-9613-62f666d42103", "name": "Product1"}, {"id": "c75e7a-001e-4d64-9613-62f666d42103", "name": null}, {"id": "c75e7a-001e-4d64-9613-62f666d42103", "name": "Product2"}, {"id": "c75e7a-001e-4d64-9613-62f666d42103", "name": null}]') v where (v.value -> 'name')::text != 'null'Producción:
[{"id": "c75e7a-001e-4d64-9613-62f666d42103", "name": "Product1"}, {"id": "c75e7a-001e-4d64-9613-62f666d42103", "name": "Product2"}]