在neo4j数据库中找到不同的路径 [英] find distinct paths in neo4j database

查看:182
本文介绍了在neo4j数据库中找到不同的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图,其中可以使用相似"关系将用户"类型的节点连接(或不连接)到其他用户"节点.

I have a graph in which nodes of type "User" can be connected (or not) to other "User" nodes using "SIMILAR" relationship.

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

I want to find all the sub-graphs (interconnected "User" nodes) ordered by the number of their nodes.

示例: 想象一下我有这些节点(关系总是"SIMILAR"类型)

Example: Imagine I have these nodes (relationship is always of type "SIMILAR")

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

我想得到:

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

使用密码或遍历.

推荐答案

在cypher中会很昂贵.

In cypher it will be expensive.

类似这样的查询:

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

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

This would work too, but is probably equally expensive :)

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

在Java中,它可能看起来像这样:

In Java it could look something like this:

@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;
}

这篇关于在neo4j数据库中找到不同的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆