0
votes

I query paths within a Neo4j graph. The path contains more than two nodes. I want to count the distinct occurences of a two-node subpath.

So in the following example I want to know the number of the resulting rows:

MATCH ()-->(n1:Label1)-->(n2:Label2)-->()
RETURN DISTINCT n1, n2

E.g. something like

RETURN count(DISTINCT n1, n2)

(which would work for a single node: RETURN count(DISTINCT n1))

How can I do this in Cypher?

1
can u explain Label1 and Label2? example- People connected to City nodes?Umesh Patil
An Example could be: (:City)<-[:LIVES_IN]-(n1:Person)-[:KNOWS]->(n2:Person)-[:LIVES-IN]->(:City) I am looking for a query that answers the question: How many unique (n1, n2)-tuples do exist that match the pattern above?thando

1 Answers

1
votes

Do this to get the number of times each distinct n1 and n2 combination is found:

MATCH ()-->(n1:Label1)-->(n2:Label2)-->()
RETURN n1, n2, COUNT(*);

Aggregating functions like COUNT use non-aggregating items in the same WITH or RETURN clause as unique "grouping keys" (so no need to use DISTINCT).

[UPDATE]

To get the number of distinct n1 and n2 combinations, you can aggregate twice in this somewhat hacky query:

MATCH ()-->(n1:Label1)-->(n2:Label2)-->()
WITH n1, n2, COUNT(*) AS ignored
RETURN COUNT(*) AS nCombos;