简体   繁体   中英

How to query extended path between nodes with Cypher in Neo4J?

I'm using Neo4J / Cypher to store / retrieve some data based on a graph model.

Let's suppose the following model: I have a set of node (type=child) that are connected through a relation (type=CONNECTED_TO).

C1 -[:CONNECTED_TO]-> C2 -[:CONNECTED_TO]-> C3 -[:CONNECTED_TO]-> C4

If I want to query a path starting from C1 to C4 without knowing intermediates:

MATCH p=
  (a:child {id:'c1Id'}) -[:CONNECTED_TO*0..]-(z:child {id:'c4Id'}) 
RETURN p

So far so good.

Now suppose that each child is contained in a parent and I want to start the query from parent ID

P1 -[:CONTAINS]-> C1
P2 -[:CONTAINS]-> C2
P3 -[:CONTAINS]-> C3
P4 -[:CONTAINS]-> C4

The query looks like:

MATCH p=
        (a:parent {id:'p1Id'})
        -[:CONTAINS]->
        (cStart:child)
        -[:CONNECTED_TO*0..]-
        (cEnd:child)
        <-[Contains]-
        (z:parent {id:'p4Id'})
RETURN p

This give me the good result. The following path:

P1 -[:CONTAINS]-> C1 -[:CONNECTED_TO]-> C2 -[:CONNECTED_TO]-> C3 -[:CONNECTED_TO]-> C4 <-[:CONTAINS]- P4

What I would like to do is to query this path from P1 to P4 using the child topology but I want to retrieve also all parents containing intermediates.

How can I improve my last cypher query to return in addition of that:

P2 -[:CONTAINS]-> C2
P3 -[:CONTAINS]-> C3

Is it possible? Maybe my model design is not appropriate for that Use case? In this case, how to improve it to address this query?

Tx

You can use list comprehension construct:

MATCH p=
        (a:parent {id:'p1Id'})
        -[:CONTAINS]->
        (cStart:child)
        -[:CONNECTED_TO*0..]-
        (cEnd:child)
        <-[Contains]-
        (z:parent {id:'p4Id'})
RETURN p,
       [n IN nodes(p)[1..-1] | (n)<-[:CONTAINS]-(:parent)][0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM