1

Is there a way to filter out null keys for my json? This is using Apache AGE extension:

SELECT json_object_agg(k, v)
FROM cypher('hermech', $$
  MATCH (a:contact_name)
  WHERE id(a) = 10133099161583644
  OPTIONAL MATCH (a)-[:DIRECT_EMAIL_ADDRESS]->(b:direct_email_address)
  OPTIONAL MATCH (a)<-[:CONTACT_NAME]-(c:account_name)
  OPTIONAL MATCH (c)-[:MAIN_PHONE_NUMBER]->(d:main_phone_number)
  OPTIONAL MATCH (c)-[:MAIN_STREET_ADDRESS]->(e:main_street_address)
  OPTIONAL MATCH (c)-[:MAIN_DOMAIN]->(f:main_domain)
  WITH [a,b,c,d,e,f] AS nodes
  UNWIND nodes AS n
  RETURN label(n) AS k, n.value AS v
$$) AS (k text, v text);

It breaks because label(n) doesn't exist since f doesn't exist in the dataset so it's a non-existent key in the json output.

I tried putting a WHERE clause after UNWIND but apparently that isn't proper syntax according to the parser.

1 Answer 1

0

Is there a way to filter out null keys for my json

Filtering Out Null Keys in JSON Output

PostgreSQL aggregate functions work with a filter clause. Not only that, some aggregates simply skip/ignore nulls (like sum() does), but json_object_agg() doesn't happen to be one of them.
demo at db<>fiddle

select json_object_agg(k,v)
from(values('a',1),('b',2),(null,3),('d',null))_(k,v);
ERROR:  field name must not be null
select json_object_agg(k,v)filter(where k is not null)
from(values('a',1),('b',2),(null,3),('d',null))_(k,v);
json_object_agg
{ "a" : 1, "b" : 2, "d" : null }
select json_object_agg(k,v)filter(where k is not null and v is not null)
from(values('a',1),('b',2),(null,3),('d',null))_(k,v);
json_object_agg
{ "a" : 1, "b" : 2 }
Sign up to request clarification or add additional context in comments.

1 Comment

This is still good stuff, but my problem is that I can't get past label(n) without it throwing an error because one of the n's doesn't exist. The solution you are proposing happens AFTER the RETURN. Maybe this question is more of an Apache AGE question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.