4

I have a Neo4j instance running. I have relationships which are weighted. One such example is representing all places in the world, and having a distance between each place.

Now it seems easy to create a relationship between two nodes, A and B:

Relationship relationship = A.createRelationshipTo(B, Relations.Knows );

But what about actual strength of the relationship. Theres been a suggestion on here as :

create a-[:`KNOWS_0.34`]->b

This works, but isn't a particularly great solution, particularly if you wanted to calculate a shortest distance dependent on the weights.

Is there anyway of doing this and storing the relationship int or float?

redrubia
  • 2,256
  • 6
  • 33
  • 47

2 Answers2

4

I wasn't aware of this, but seems you can set additional properties when creating a Relationship:

Relationship relAB = createRelationship( nodeA, nodeC, "length", 2d );
redrubia
  • 2,256
  • 6
  • 33
  • 47
  • 2
    Neo4j is a property graph, this means you can have an arbitrary number of properties on both nodes and relationships – RaduK Mar 04 '14 at 08:34
  • do you know what functionality there is for paths, whereby I want a path from one node to another, being the shortest and yet using the biggest weights? – redrubia Mar 04 '14 at 13:03
  • 1
    You could retrieve all the shortest paths between the two nodes, and then compare their weight: http://docs.neo4j.org/chunked/milestone/query-match.html#_shortest_path – RaduK Mar 04 '14 at 13:50
  • 1
    This function finds, the shortest path (singular not plural :( ) – redrubia Mar 04 '14 at 13:57
  • 2
    Well, you should have read the whole section :). You have both 'allShortestPaths' and 'shortestPath' – RaduK Mar 04 '14 at 14:13
3

It's a good approach to use a weight property on your relationship!

Take a look at Graph Algorithm examples in the Neo4j tutorial pages. It describes various ways to find shortest paths using weighted relationships e.g. using Dijkstra or A* algorithms. A great dijkstra example can be found here.

tstorms
  • 4,941
  • 1
  • 25
  • 47