Search code examples
countneo4jdistinctcypherrelationships

Neo4j 2.1+ - Cypher - Return number of times a relationship appears when using DISTINCT


I'm struggling with maybe a simple query but I'm unable to find an answer :

Let's give the following simple schema :

Nodes :

Package1
Library1
Library2
Library3

Relationships:

(Library1)-[:USES {in_version:'1.1'}]->(Package1)
(Library2)-[:USES {in_version:'1.2'}]->(Package1)
(Library3)-[:USES {in_version:'1.2'}]->(Package1)

Simple no ?

So what I would like is to return my package node, and group relationships by distinct in_version property and the number of times the in_version is used

This should be the return I would like to have :

package    |  in_version  |  usage  |
Package 1  |  1.1         |  1      |
Package 1  |  1.2         |  2      |

I tried to combine distinct, collect, ..but I'm struggling currently

Edit

My last query is as follow :

MATCH (p:Package)<-[r:USES]-()
WHERE p.name = 'Package1'
WITH p, collect(r) as v
UNWIND v as x
RETURN distinct x.in_version, count(x) as usage
ORDER BY usage DESC

And I can get the versions and the usage correctly. But if I want to add the package name to the return, cypher complain about the '.' in x.in_version

MATCH (p:Package)<-[r:USES]-()
WHERE p.name = 'Package1'
WITH p, collect(r) as v
UNWIND v as x
RETURN p.name, distinct x.in_version, count(x) as usage
ORDER BY usage DESC

While the p.name is not necessary for this query as I know it in advance, the goal is to 1st filter packages having the most uses relations and then return this query by package in one time

Thanks in advance

Chris


Solution

  • Try this query

    match (lib)-[r:USES]->(pack)
    where has(r.in_version)
    with pack, collect(r.in_version) as vers,lib
    with pack,vers ,collect(lib) as libs,count(lib) as usage
    return pack as package,vers as in_version,usage