Querying Recursive Relationship Chains in Neo4j with Cypher
Asked Answered
C

1

2

I have a graph database that is modeling the metadata for messages and the fields that can be contained on those messages. Some of those fields can be "groups" which are groups of other fields. What I am attempting to ask Neo is "what messages are using this group?". The following is a list of the path types that can be used to get from a message to a group:

message-[:INLINE]->group  (the fields of a group are used inline on a message)
message-[:FIELDREF]->(fref)-[:FIELD]->(field)-[:DATATYPE]->group (the group is used as a data type by a field on the message)

The second chain is recursive. In other words, the -[:FIELDREF]->(fref)-[:FIELD]->(field)-[:DATATYPE]-(group) segment can happen over and over again before finally reaching the group I'm interested in.

So, what I want to know is, how do I ask for a repeating chain of relationships rather than just a multiple (e.g. * after the relationship name) on each individual element in the path?

To recap, you can either get to a group from a message by traversing an [:INLINE] relationship, which can then follow n number of "fieldref-field-datatype-group" chains.. OR you can get to a group from a message by traversing n number of "fieldref-field-datatype-group" chains.

START group=node({sourceGroupId})
... ? ? ? ...

So I want something like [?:INLINE]-> 0..n of (fieldref-field-datatype-group) chains.

Any thoughts?

Crenelation answered 23/5, 2013 at 16:6 Comment(0)
M
5

According to the Cypher reference at http://docs.neo4j.org/chunked/milestone/query-match.html ...

12.2.13. Variable length relationships Nodes that are a variable number of relationship→node hops away can be found using the following syntax: -[:TYPE*minHops..maxHops]->. minHops and maxHops are optional and default to 1 and infinity respectively. When no bounds are given the dots may be omitted.

An example of what I think you seek is below. I set the minimum at two.

start n=node:node_auto_index(name='Neo') match n-[r:KNOWS*2..]-m return n as Neo,r,m

You can test this query verbatim at http://console.neo4j.org

Mikael answered 23/5, 2013 at 20:43 Comment(2)
Yes I knew about the asterisk. I was actually trying to be too complex and describe an exact shape when I could've just told Neo that I want "any path, of any length, from a message to a group", like this: msg-[?:INLINE|FIELDREF|FIELD|DATATYPE*]->nCrenelation
Reference link is broken in 2024: docs.neo4j.org/chunked/milestone/query-match.htmlTwinflower

© 2022 - 2024 — McMap. All rights reserved.