ShenLei
ShenLei

Reputation: 587

How to match all paths that ends with nodes with common properties in Neo4j?

I would like to match all paths from one given node.

         -->(c: {name:"*Tom*"})
        /
(a)-->(b)-->(d: {name:"*Tom*"})
        \           
         -->(e: {name:"*Tom*"})

These paths have specified structure that: - the name of all children of the second-last node (b) should contain "Tom" substring.

How to write correct Cypher?

Upvotes: 0

Views: 368

Answers (1)

Gabor Szarnyas
Gabor Szarnyas

Reputation: 5047

Let's recreate the dataset:

CREATE
  (a:Person {name: 'Start'}),
  (b:Person),
  (c:Person {name: 'Tommy Lee Jones'}),
  (d:Person {name: 'Tom Hanks'}),
  (e:Person {name: 'Tom the Cat'}),
  (a)-[:FRIEND]->(b),
  (b)-[:FRIEND]->(c),
  (b)-[:FRIEND]->(d),
  (b)-[:FRIEND]->(e)

As you said in the comment, all requires a list. To get a list, you should use the collect function on the neighbours of b:

MATCH (:Person)-[:FRIEND]->(b:Person)-[:FRIEND]->(bn:Person)
WITH b, collect(bn) AS bns
WHERE all(bn in bns where bn.name =~ '.*Tom.*')
RETURN b, bns

We call b's neighbours as bn and collect them to a bns list.

Upvotes: 3

Related Questions