Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neo4j cypher to count and display all the relationship between two given nodes

Here I am using neo4j rest api, in first step I want to collect information like how many relationships are there between two given nodes.

Sample : MATCH (n:Node {id: {parameter1}})-[r:someType]-(m:Node {id: {parameter2}}) RETURN COUNT(r)

Then I would like to collect all the values assigned to the edges so I can calculate further calculations. I need all the different types of relationships and their properties between two given nodes.

If it is possible I would like to do it in single cypher.

like image 216
Sagiruddin Mondal Avatar asked Jun 08 '14 10:06

Sagiruddin Mondal


People also ask

How do I return all nodes and relationships in Neo4j?

Return all elements When you want to return all nodes, relationships and paths found in a query, you can use the * symbol.

How do you count nodes in Cypher?

Using count(*) to return the number of nodes The function count(*) can be used to return the number of nodes; for example, the number of nodes connected to some node n . The labels and age property of the start node n and the number of nodes related to n are returned.

How do you perform and aggregation in Cypher?

The Cypher query offers aggregation similar to GROUP BY offered by SQL. The aggregate function can take multiple values and can calculate the aggregated values for them. In this recipe, we will learn the common aggregation techniques, with the help of examples.


1 Answers

Then I would like to collect all the values assigned to the edges

MATCH (n:Node {id: {parameter1}})-[r:someType]-(m:Node {id: {parameter2}})
RETURN COUNT(r) AS count, COLLECT(r) AS rels 

Note that the only thing I changed was adding collect(r) AS rels to the return, which gives you a collection of Relationship objects representing all edges with label someType between these nodes.

To get all edges of any type:

MATCH (n:Node {id: {parameter1}})-[r]-(m:Node {id: {parameter2}})
RETURN COUNT(r) AS count, collect(r) AS rels ORDER BY labels(r)

Remove the label requirement from the MATCH to return a collection of all relationships of any type. Order that collection by label, so that the list of relationships returned is sorted by type, making it easy for you to distinguish between them as needed for the purposes of your "further calculations"

This code is untested, and I'm not 100% sure you can call labels on a collection. If not, let me know and I'll provide an alternate solution.

like image 86
drew moore Avatar answered Sep 27 '22 16:09

drew moore