Search code examples
asp.net-mvcgraphneo4jcypherneo4jclient

Neo4j Return Distinct Node With Least Amount of Hops


I have the following data:

A --> B
B --> C

Consider this query:

START n = node(A, B)
MATCH p = n-[*..2]-(x)
RETURN n.Name, x.Name, length(p)

Starting with 2 input nodes, traverse to other nodes with no more than 2 hops.

The following is returned:

==> +------------------------------------------------+
==> | n.Name       | x.Name              | length(p) |
==> +------------------------------------------------+
==> | "A"          | "C"                 | 2         |
==> | "B"          | "C"                 | 1         |

Backstory: In my app you can search for interests (multiple at a time). Each interest can have related interests. Sometimes the input interests share common interests which results in duplicated interests.


Solution

  • It looks like simply calling MIN does what I'm looking for:

    RETURN x.Name, min(length(p))
    

    So it's going to group by x.Name and take the smallest hop column.

    http://docs.neo4j.org/chunked/stable/query-aggregation.html

    Aggregation can be done over all the matching sub graphs, or it can be further divided by introducing key values. These are non-aggregate expressions, that are used to group the values going into the aggregate functions.