1
votes

I need to find the N nodes "nearest" to a given node in a graph, meaning the ones with least combined weight of relationships along the path from given node. Is is possible to do so with a pure Cypher only solution? I was looking about path functions but couldn't find a viable way to express my query.

Moreover, is it possible to assign a default weight to a relationship at query time, according to its type/label (or somehow else map the relationship type to the weight)? The idea is to experiment with different weights without having to change a property for every relationship. Otherwise I would have to change the weight property's value to each relationship and re-do it to before each query, which is very time-consuming (my graph has around 10M relationships). Again, a pure Cypher solution would be the best, or please point me in the right direction.

1
Have you looked at REDUCE? You can easily sum relationship weights over a path and return k nodes with the lowest sum using LIMIT k. docs.neo4j.org/chunked/stable/…Nicole White

1 Answers

2
votes

Please use variable length Cypher queries to find the nearest nodes from a single node.

MATCH (n:Start { id: 0 }),
  (n)-[:CONNECTED*0..2]-(x)
RETURN x

Note that the syntax [CONNECTED*0..2] is a range parameter specifying the min and max relationship distance from a given node, with relationship type CONNECTED.

You can swap this relationship type for other types.

In the case you wanted to traverse variably from the start node to surrounding nodes but constrain via a stop criteria to a threshold, that is a bit more difficult. For these kinds of things it is useful to get acquainted with Neo4j's spatial plugin. A good starting point to learn more about Neo4j spatial can be found in this blog post: http://neo4j.com/blog/neo4j-spatial-part1-finding-things-close-to-other-things

The post is a little outdated but if you do some Google searching you can find more updated materials.

GitHub repository: https://github.com/neo4j-contrib/spatial