Say I have :
MATCH p = (:Organization)-[*0..1]->(:Group)-[*0..1]->(:User)
I would like to show all paths of the form Organization->Group->User, but if some suffix of the path is missing, for example Organization->Group or only Organization, I would like to show it as well (that is the reason I have set the path length constraint).
Unfortunately, the current query outputs only full paths (despite of the length constraint).
If I try to remove the label constraint:
MATCH p = (:Organization)-[*0..2]->()
This works, but gives me a lot of extra paths I don't want in my results (i.e Organization to nodes which are not labeled with Group).
I am aware this can be solved by performing unions with each query to stand for a specific path form, but that seems like a very naive and inefficient way to solve this.
I am sure this can be solved with one query based on MATCH p = .... and RETURN p.
Did you test OPTIONAL keyword?
OPTIONAL MATCH p = (:Organization)-[*0..1]->(:Group)-[*0..1]->(:User)
Hello, i'll try to explain for what I understand in a query:
MATCH p = (:Organization)-[*0..2]->(:User)<-[*0..1]-(:Group)
The "Organization" and the "Group" if are in a fixed schema it can be a solution? For fixed I mean a "Group" is within a "Organization" and not contrary. And it can or cannot be a "Group" into "Organization". The "Organization" includes 2 hops and you can find a "Organization"-"User"-"User" path depends on type of structure builted and I believe if you want to avoid this, you must include a WHERE or WITH clause.
I was familiar with the OPTIONAL keyword, unfortunately this does not do the trick.
MATCH p = (:Organization)-[*0..1]->(:Group)
OPTIONAL MATCH p = (:Organization)-[*0..1]->(:Group)
same results return - only direct links between Organizations and Groups, even though there exists in my graph some Organizations with no links to Groups. These are not shown in the output, even if the OPTIONAL keyword is used.
This solution might work but has 2 serious issues:
- You are allowing 2-hop connections from Organization to User without the constraint of the node in between being a Group.
- It does not scale well. If the desired full path would consist of a larger number of node types (say max possible path length 5-6 and not 2), you won't be able to form your query using this technique.
I might have found a different solution, yet I'm not sure it's the most efficient to go with.
Understanding that a 0 zero length path is basically a path from a node to itself, we can say:
MATCH p = (a:Organization)-[*0..1]->(b)-[*0..1]->(c)
WHERE (b:Group or a=b) and (c:User or b=c)
Still looking for something more clean and scalable for longer paths.