How to filter results using node label in neo4j cypher?

I have a graph database that displays connections between buildings and bus stations, where the graph contains other connecting elements, such as roads and intersections (among many node types).

What I'm trying to understand is how to filter the path down to return only certain types of node. I have two related issues that I am currently struggling with.

Question 1: How to return node labels along the way?

It seems like a logical first step is to determine what types of nodes are found along the path.

I tried the following:

MATCH p=(a:Building)­-[:CONNECTED_TO*..5]­-(b:Bus) 
WITH nodes(p) AS nodes 
RETURN DISTINCT labels(nodes);

However, I get a type exception error in which label () expects data of type node, not Collection. I would like to dynamically know what types of nodes are on my paths so that I can ultimately filter my paths.

Question 2: How can I return a subset of nodes in a path that matches the label that I identified in the first step?

Let's say I found that between (a:Building)and (d1:Bus), (d2:Bus)I can find the nodes (:Intersection)and (:Street).

This is a simplified model of my graph:

(a:Building)­­--(:Street)­--­(:Street)--­­(b1:Bus) 
             \­­(:Street)--­­(:Intersection)­­--(:Street)--­­(b2:Bus)

I wrote an instruction MATCHthat will look for all possible paths between nodes (:Building)and (:Bus). What do I need to do next to the filter to selectively return Street nodes?

MATCH p=(a:Building)-[r:CONNECTED_TO*]-(b:Bus)
  // Insert logic to only return (:Street) nodes from p

Any advice on this would be greatly appreciated!

+4
2
  • :

    MATCH p=(a:Building)-[:CONNECTED_TO*..5]-(b:Bus)
    WITH NODES(p) AS nodes
    UNWIND nodes AS n
    WITH LABELS(n) AS ls
    UNWIND ls AS label
    RETURN DISTINCT label;
    
  • Street.

    MATCH p=(a:Building)-[r:CONNECTED_TO*]-(b:Bus)
    WITH NODES(p) AS nodes
    UNWIND nodes AS n
    WITH n
    WHERE 'Street' IN LABELS(n)
    RETURN n;
    
+3

, - ... . , : : , , , , , , , , .

, , , , , : Building to: Bus, cybersam , . , .

, .

1, , :

MATCH p=(:Building)-[:CONNECTED_TO*..5]-(:Bus)
WITH NODES(p) AS nodes
WITH REDUCE(myLabels = [], node in nodes | myLabels + labels(node)) as myLabels
RETURN DISTINCT myLabels

2 :

MATCH p=(:Building)-[:CONNECTED_TO*..5]-(:Bus)
WITH NODES(p) AS nodes
WITH FILTER(node in nodes WHERE (node:Street)) as pathStreets
RETURN pathStreets

, , , . , , , .

, . , , , : CONNECTED_TO , , , , , , .

0

Source: https://habr.com/ru/post/1656001/


All Articles