drdot
drdot

Reputation: 3347

How to limit the amount of certain node types in my path?

Say I have the following graph:

(:A) -> (:B {hasAttr: 'yes'}) -> (:C) -> (:B {hasAttr: 'yes'})

I want to find out the path between node type A and node type B. But I only need the path that contains one node type B. So the query return should be

(:A) -> (:B {hasAttr: 'yes'})

What is the right query?

Upvotes: 0

Views: 56

Answers (2)

jose_bacoy
jose_bacoy

Reputation: 12704

Graphileon is correct. Use the function SINGLE() to return nodes with exactly one node that has a property.hasAttr = 'yes'. Below is a working query.

MATCH 
    p = (:A)-->(:B)
WHERE
    single(var IN nodes(p) WHERE var.hasAttr = 'yes')
RETURN p


Sample graph found in https://neo4j.com/docs/cypher-manual/current/functions/predicate/#functions-single 

MATCH p = (n)-->(b)
WHERE
  n.name = 'Alice'
 AND single(var IN nodes(p) WHERE var.eyes = 'blue')
RETURN p

Result:
╒══════════════════════════════════════════════════════════════════════╕
│"p"                                                                   │
╞══════════════════════════════════════════════════════════════════════╡
│[{"name":"Alice","eyes":"brown","age":38},{},{"name":"Bob","eyes":"blu│
│e","age":25}]                                                         │
└──────────────────────────────────────────────────────────────────────┘

Upvotes: 0

Graphileon
Graphileon

Reputation: 5385

You can use the SINGLE() predicate function (see https://neo4j.com/docs/cypher-manual/current/functions/predicate/#functions-single)

MATCH p = ...
WHERE SINGLE(node IN nodes(p) WHERE node:B)

Upvotes: 3

Related Questions