Thursday, January 2, 2014

Simplifying graphs with Neo4j and Cypher


Something important in a knowledge map is that is has to be as simple as possible.
For example, let's say the node A depends on node B and node B depends on Node C:

A->B->C

This tree is identical, in the context of a knowledge map, to this more complex one:

A->B-C
|->C

In this case, the brach from A to C is reduntant as this relation is contained in the branch A->B->C.

A way to simplify this second tree is using Neo4j and Cypher.

We can create the tree this way:

create (nodeA{name:'nodeA'}), (nodeB{name:'nodeB'}), (nodeC{name:'nodeC'}), (nodeA)-[:DEPENDS]->(nodeB), (nodeB)-[:DEPENDS]->(nodeC), (nodeA)-[:DEPENDS]->(nodeC)

To simplify it just execute this Cypher query:

match a-[r:DEPENDS]->c
where a-[:DEPENDS*2..]->c
delete r

Here we are deleting all the DEPENDS relations that connect two nodes where there is another longer path connecting them.

In this case, the relation to delete is A-C as there is another longer path: A->B->C
Try it yourself: console.neo4j.org

No comments:

Post a Comment