在neo4j数据库中找到不同的路径

时间:2014-01-19 15:03:11

标签: neo4j

我有一个图表,其中“User”类型的节点可以使用“SIMILAR”关系连接(或不连接)到其他“User”节点。

我想找到按节点数排序的所有子图(互连的“用户”节点)。

实施例: 想象一下,我有这些节点(关系总是类型为“SIMILAR”)

A -> B,
A -> C,
D -> B,
E -> F,
Z

我想得到:

[A,B,C,D];
[E,F];
[Z];

使用Cypher或遍历。

1 个答案:

答案 0 :(得分:4)

在密码中它会很昂贵。

像这样的查询:

MATCH m WITH collect(m) as all
MATCH n
RETURN distinct [x in all WHERE (n)-[*0..]-(x) | x.name] as cluster

这也可以,但可能同样昂贵:)

MATCH n-[*0..]-m
WITH n, m
ORDER BY id(m)
WITH n, collect(m.name) as cluster
RETURN distinct cluster

在Java中它看起来像这样:

@Test
public void testSimpleCluster() throws Exception {
    createData();
    try (Transaction tx = db.beginTx()) {
        TraversalDescription traversal = db.traversalDescription().depthFirst().uniqueness(Uniqueness.NODE_GLOBAL);
        Map<Node, Set<Node>> clusters = new HashMap<>();
        GlobalGraphOperations ops = GlobalGraphOperations.at(db);
        for (Node node : ops.getAllNodes()) {
            if (inCluster(node, clusters) != null) continue;
            clusters.put(node, IteratorUtil.addToCollection(traversal.traverse(node).nodes(), new HashSet<Node>()));
        }
        System.out.println("clusters = " + clusters.values());
        tx.success();
    }
}

private Node inCluster(Node node, Map<Node, Set<Node>> clusters) {
    for (Map.Entry<Node, Set<Node>> entry : clusters.entrySet()) {
        if (entry.getValue().contains(node)) return entry.getKey();
    }
    return null;
}

private void createData() {
    try (Transaction tx = db.beginTx()) {
        Node a = node("a");
        Node b = node("b");
        Node c = node("c");
        Node d = node("d");
        Node e = node("e");
        Node f = node("f");
        Node z = node("z");
        connect(a, b);
        connect(a, c);
        connect(d, b);
        connect(e, f);
        tx.success();
    }
}

private void connect(Node a, Node b) {
    a.createRelationshipTo(b, SIMILAR);
}

private Node node(String name) {
    Node node = db.createNode();
    node.setProperty("name", name);
    return node;
}