Simple query returns (no records)

Yo! Having a hard time with a simple query here :sweat_smile:
This is the query:

MATCH (a:Person {name: "Stefan"})

MATCH (p:Person {name: "not_a_real_name"})
CALL apoc.path.subgraphNodes(p, {
    relationshipFilter: "KNOWS"
})
YIELD node AS b

RETURN a

I'm trying to keep the a-node even if the called procedure returns (no records). I think i'm looking for som kind of OPTIONAL MATCH, but don't know how. If I change "not_a_real_name" with "Praveena", a is correct.

Here's the recreation data:

MERGE (mark:Person:DevRel {name: "Mark"})
MERGE (lju:Person:DevRel {name: "Lju"})
MERGE (praveena:Person:Engineering {name: "Praveena"})
MERGE (zhen:Person:Engineering {name: "Zhen"})
MERGE (martin:Person:Engineering {name: "Martin"})
MERGE (joe:Person:Field {name: "Joe"})
MERGE (stefan:Person:Field {name: "Stefan"})
MERGE (alicia:Person:Product {name: "Alicia"})
MERGE (jake:Person:Product {name: "Jake"})
MERGE (john:Person:Product {name: "John"})
MERGE (jonny:Person:Sales {name: "Jonny"})
MERGE (anthony:Person:Sales {name: "Anthony"})
MERGE (rik:Person:Sales {name: "Rik"})

MERGE (zhen)-[:KNOWS]-(stefan)
MERGE (zhen)-[:KNOWS]-(lju)
MERGE (zhen)-[:KNOWS]-(praveena)
MERGE (zhen)-[:KNOWS]-(martin)
MERGE (mark)-[:KNOWS]-(jake)
MERGE (alicia)-[:KNOWS]-(jake)
MERGE (jonny)-[:KNOWS]-(anthony)
MERGE (john)-[:KNOWS]-(rik)

MERGE (alicia)-[:FOLLOWS]->(joe)
MERGE (joe)-[:FOLLOWS]->(mark)
MERGE (joe)-[:FOLLOWS]->(praveena)
MERGE (joe)-[:FOLLOWS]->(zhen)
MERGE (mark)-[:FOLLOWS]->(stefan)
MERGE (stefan)-[:FOLLOWS]->(joe)
MERGE (praveena)-[:FOLLOWS]->(joe)
MERGE (lju)-[:FOLLOWS]->(jake)
MERGE (alicia)-[:FOLLOWS]->(jonny)
MERGE (zhen)-[:FOLLOWS]->(john)
MERGE (anthony)-[:FOLLOWS]->(joe)

Try this:

MATCH (a:Person {name: "Stefan"})
Call {
    MATCH (p:Person {name: "xxxx"})
    CALL apoc.path.subgraphNodes(p, {relationshipFilter: "KNOWS"})
    YIELD node
    return collect(node) as subGraphNodes
}
return a, subGraphNodes

Thanks for the nice and simple answer!
I also got an alternative answer on stackoverflow, using the apoc.when procedure like so:

MATCH (a:Person {name: "Stefan"})
OPTIONAL MATCH (p:Person {name: "not_a_real_name"})
CALL apoc.when(p is not null,
  'CALL apoc.path.subgraphNodes(person, {
    relationshipFilter: "KNOWS"}) YIELD node AS b RETURN b',
  'RETURN NULL',
  {person:p}
)
YIELD value as nodes
RETURN  a, nodes

Don't know what fits my usecase the best.

1 Like

Just a little update with some useful logic for those who want the nodes (not in a list) or null:

MATCH (a:Person {name: "Stefan"})
Call {
    MATCH (p:Person {name: "xxxx"})
    CALL apoc.path.subgraphNodes(p, {relationshipFilter: "KNOWS"})
    YIELD node
    return collect(node) as subGraphNodesList
}
UNWIND (CASE subGraphNodesList WHEN [] then [null] else subGraphNodesList end) as subGraphNodes
RETURN subGraphNodes, a