Match and return node only if node exist

Can someone please help me with my query

MATCH (n:label1)<-[rel1]-(m:label2)-[rel2]->(o:label3)-->(p:label4)
WHERE m.name="my_name"
RETURN n.name, m.name, o.name, p.name, rel1.name, rel2.name

which fails, if n or o or p doesn't exist. But is there a way to still get the output if a label is missing.

Let's say "o" and "p" are missing for a few subgraphs and "n" is missing for few subgraphs. How can I handle this.

I can't write multiple queries, because I have totally 11 different labels and the combination differs a lot.

Thanks in advance.

You should specify the optional parts of the pattern with OPTIONAL MATCH

1 Like

As @florent_biville suggested, use OPTIONAL MATCH to return 'null' when a match is not found, instead of terminating the query. Here is one approach:'

OPTIONAL MATCH (m:label2)
WHERE m.name="my_name"
OPTIONAL MATCH (n:label1)<-[rel1]-(m)-[rel2]->(o:label3)-->(p:label4)
RETURN n.name, m.name, o.name, p.name, rel1.name, rel2.name

Thank you for your response. But the query you provided doesn't work. Below I have have attached a subgraph and the names.
image

For this connection, the below query works

But if I have a query like the below it gives me nothing

If I try the query you suggested I only get the output for label2

So if I then try to call label1 with OPTIONAL MATCH it's start to fetch the other subgraphs as well

I hope this helps understand my issue.

Can you explain a little more about what you are trying to accomplish?

When matching you are specifying the exact pattern you are looking for. If it can not be found, the search stops and a result it not returned.

In your initial query you ask for a path where the given node ‘m’ is related to a label1 node and a label3 node. You will get zero paths if ‘m’ is only related to one other node, one path if related to one each, and multiple paths if related to more than one each of label1 and label3 nodes. .

MATCH (n:label1)<-[rel1]-(m:label2)-[rel2]->(o:label3)
WHERE m.name="my_name"
RETURN n.name, m.name, o.name, p.name, rel1.name, rel2.name

If you add another constraint, like ‘o’ itself being related to a label4 node, then again, no result if the new relation does not exists.

In this case, you may do the following if the label4 node is optional.

MATCH (n:label1)<-[rel1]-(m:label2)-[rel2]->(o:label3)
WHERE m.name="my_name"
OPTIONAL MATCH (o)—>(p:label4)
RETURN n.name, m.name, o.name, p.name, rel1.name, rel2.name, p.name
1 Like

Sorry for the confusion, but this query solved it. Thanks a lot for your time.

No worries. Glad to help

1 Like