tmptplayer
tmptplayer

Reputation: 509

Cypher: How to traverse across any relationship except for a specific label

Given a node in a cypher defined graph with a variable and uncertain number and type of incoming and outgoing relationships, how can I define in a cypher query a variable number of traversals which follow all relationships except for those of a specific type.

For example, I'd like to find and return all nodes 1 - 4 relationship traversals away from a starting point (plus the original), but I do not want to traverse any relationships labeled :CREATED_BY:

MATCH (t:Thing {name: 'Starting Point'})-[x*1..4]-(o)
WHERE NOT x:CREATED_BY
RETURN t, o

This returned an error because x, in this case, is a list of relationships instead of a single relationship.

In an ideal world, I'd love it if I could do something like:

MATCH (t:Thing {name: 'Starting Point'})-[x(NOT :CREATED_BY)*1..4]-(o)

Or some other pithy expression within the Match clause. If that does not syntactically exist, then a simple where statement would be preferred. If not, my last avenue of attack is to treat x as a list, decompose it and then apply some conditional that for any given element it should not equal the relationship to be excluded. My Cypher isn't good enough to construct this piece yet, and I'm really hoping that this isn't an edge case in the language and a simple way of handling this query exists.

Thanks!

Upvotes: 0

Views: 1554

Answers (1)

stellasia
stellasia

Reputation: 5612

You can go with a WHERE statement like this:

MATCH (t:Thing {name: 'Starting Point'})-[x*1..4]-(o)
WHERE all(r in x WHERE type(r) <> 'CREATED_BY')
RETURN t, o

It basically loops over all relationships in r, extracts the relationship type and compare it to 'CREATED_BY'. The all predicate ensures all relationships in the path are not of the type 'CREATED_BY'.

Check the documentation for the all function here: https://neo4j.com/docs/cypher-manual/current/functions/predicate/#functions-all

You can also check the APOC advanced querying tool (https://neo4j.com/labs/apoc/4.1/graph-querying/), especially the path expander procedures, but as far as I know, you can't blacklist a certain relationship type (only whitelist the allowed ones). If you can turn your exclusion into a inclusion list, it would be a nice alternative.

Upvotes: 1

Related Questions