Running multiple MATCHes without returning null

Hi I have a sample query if you'd like to see an idea of the graph I'm going to be referring to:

CREATE (u:User {name: "Tim Cook"})-[:FOLLOWS]->(t:Thing {name: "Italy"}), (t)<-[:TAGGED]-(p:Post {name: "Post 1"})<-[:WROTE]-(u1:User {name: "Elon Musk"}), (u)-[:FOLLOWS]->(u2:User {name: "Oprah"})-[:WROTE]->(p1:Post {name: "Post 2"}), (u)-[:FOLLOWS]->(u3:User {name: "Joe Biden"})-[:WROTE]->(p2:Post {name: "Post 3"})

Also here:

I am trying to get all posts where the user either follows the author directly (someone who "WROTE" a post) OR where the person follows a Thing that was "TAGGED" in a post.

So in the example query, if you are Tim Cook, you should receive Posts 2 and 3 because you follow the authors directly, and Post 1 because you follow Italy that was TAGGED in that post.

I've been searching everywhere, it's a hard thing to search for. Landed here. I'm using "OPTIONAL" so that if the user isn't following any people the first one doesn't crash the whole query, or if they aren't following any things, the second one doesn't crash. However, with how I did it below, it returns Null for either of the queries that are empty.

So if there are no matches for the first part and 6 for the second, I end up with an array of length 7. [null, post1, post2, ...post6].

OPTIONAL MATCH (this)-[:FOLLOWS]->(u1)-[:WROTE]->(post:Post)
OPTIONAL MATCH (this)-[:FOLLOWS]->(t:Thing)<-[:TAGGED]-(post:Post)

this refers to the Tim Cook user node in the above example.

I also would like to return if the user follows the author (the User who "WROTE"). So I think I can add an "EXISTS" or is there a way to specify which query returned a post? E.g. if the post was returned by the first MATCH above, then they clearly follow the author. If returned by the 2nd, and not the first, then they don't. What's the best way to tackle this query/how should I be doing this instead, please? Thank you in advance!

Answered here : neo4j - How can I run a multiple-MATCH search without returning null? - Stack Overflow and validated by the author.

1 Like