Search code examples
neo4jcyphernodesrelationships

Neo4j - extract property data of nodes in a path and the relationship pointing to those nodes


I'd like to write a compact query for the following data structure.

Node n1 up to node 1000 are connected via the relation 'rel1' Each node n has the property n.name Another node (only one exists) Q has relation 'rel2' to each node n1 with a relationship property q.value

(n1)-[rel1]->(n2)-[rel1]->(n3)--[rel1]-......->(n1000)
(Q)-[rel2]->(n1), (Q)-[rel2]->(n2),(Q)-[rel2]->(n3)....... (Q)-[rel2]->(n1000)

I want to extract this data: a list of the 1000 names (n.name) in order of appearance and a list of the 1000 q.values that point to each node n

I get as far as retrieving all the names nodes n by using a collection function

match p=(n)-[r:rel1*..]->(m) where  n.nodeNumber = 1 and m.nodeNumber=1000 RETURN extract(n IN nodes(p)| n.name) AS name 
ORDER BY length(p) DESC
LIMIT 1

Can I easily extract all the q.values that point to these nodes as well? Ideally in one statement.


Solution

  • Just to correct the previous elegant command. a ) was missing and you need to specify the length of the path to search. By default it is only 15 or so. I added 1100 in the command as 1000 nodes were given. I also changed n to nlist as Neo4j complained about n being declared twice.

    The updated command is here:

    match p=shortestPath((n:Label)-[r:rel1*..1500]->(m:Label))
    where  n.nodeNumber = 1 and m.nodeNumber=1000 
    UNWIND nodes(p) as nlist
    MATCH (nlist)<-[:rel2]-(q:Q)
    RETURN nlist.name, q.value;