用Neo4j提取一棵树 [英] Fetch a tree with Neo4j

查看:694
本文介绍了用Neo4j提取一棵树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到Neo4j REST服务器中的树木树林,我试图返回给定根顶点的一棵树.

Given a forest of trees in a Neo4j REST server, I`m trying to return a single tree given the root vertex.

由于每棵树都很大,我需要对所有顶点和边进行重复数据删除的列表,以便能够在客户端重建完整的树.

Being each tree quite large, I need a de-duplicated list of all vertices and edges in order to be able to reconstruct the full tree on the client side.

我在MATCH (r:root)-[*]->()周围尝试了多种组合,但它们会返回从根开始的任何路径,因此有很多重复项:

I tried multiple combinations around MATCH (r:root)-[*]->() but they return any path starting from the root, thus with lots of duplicates:

MATCH p = (r:root)-[*]->(x)
RETURN nodes(p) AS Vertices, rels(p) AS Edges";

这将返回每个路径,如下所示,每次都重复每个节点:

this returns each and every path as follows, repeating each node every time:

a->b
a->b->c
a->b->c->d

等...

相反,我需要一个结果

{
    Vertices: [a, b, c, d],
    Edges: [[a, b], [b, c], [c, d]]
}

如果相关的话,我正在使用带有Seraph的Node.js,但是我并没有严格地绑定到该库.

I'm using Node.js with Seraph, if relevant, but I`m not strictly bound to that library.

推荐答案

因此,首先,您可能想添加WHERE子句以确保路径始终以叶子结尾:

So first off, you might want to add a WHERE clause to make sure that your path is always ending with a leaf:

MATCH p = (r:root)-[*]->(x)
WHERE NOT(x-->())
RETURN nodes(p) AS Vertices, rels(p) AS Edges";

因此,第二,如果要一次性获取所有节点和关系,则可能需要执行两个查询:

So secondly, if you want to get all of the nodes and relationships in one go, you may need to execute two queries:

MATCH p = (r:root)-[*]->(x)
WHERE NOT(x-->())
UNWIND nodes(p) AS Vertex
RETURN DISTINCT Vertex;

MATCH p = (r:root)-[*]->(x)
WHERE NOT(x-->())
UNWIND rels(p) AS Edge
RETURN DISTINCT startNode(Edge), endNode(Edge);

更新(迈克尔)

MATCH p = (r:root)-[*]->(x)
WHERE NOT(x-->())
UNWIND nodes(p) AS Vertex
WITH collect(DISTINCT Vertex) as nodes, p
UNWIND rels(p) AS Edge
RETURN nodes, collect(distinct Edge) as rels

Update2(Michael)

我找到了一种更紧凑的方法

I found an even more compact way

MATCH p = (:root)-[r*]->(x)
RETURN collect(DISTINCT id(x)) as nodes, [r in collect(distinct last(r)) | [id(startNode(r)),id(endNode(r))]] as rels

如果您还想包含根节点,请使用*0..

If you also want to include the root node, use *0..

这篇关于用Neo4j提取一棵树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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