繁体   English   中英

Neo4j / Cypher-查找具有2个以上链接的已连接节点

[英]Neo4j/Cypher - find connected nodes that have more than 2 links

我有一个如下图(为简单起见,删除了所有标签或链接方向)

简单的示例图

我想从节点(c)开始,仅查找具有两个以上相邻边的那些节点,以及从(c)到它们的路径。

在上面的示例中,节点(b)具有3个相邻边(ba,bc,bg),节点(e)具有4个相邻边(ed,ef,eh,eh),因此我想将路径返回到just( b)和(e)。

我也不想返回路径(一),(六),(八),(g)或(J) -我想停止遍历当计数满足。

我尝试了以下方法:

START n=node(c)
MATCH (n)-[r*]-(m)-[rx]-(o)
WITH m AS m, n AS n, r AS r, count(rx) as cnt
WHERE cnt > 2
RETURN n, r, m, cnt;

...但是除了b和e之外,它还返回到a,g,h,f和j的路径。 对于大图来说,这也是非常昂贵的。

非常感谢您的帮助。

编辑:

我提供的示例图像过度简化了我的数据,因此最初的建议不起作用(请参阅http://console.neo4j.org/?id=d6feml ),因此下面提供了一个新的图像示例。

我想要 :到e a b的路径-和以前一样。

我不想 :返回路径到h。

在此处输入图片说明

再次感谢neo4jers ...

有趣的是,我使用http://console.neo4j.org/r/qc7log将其放入Neo4j控制台。

您要查找的Cypher语句是:

START n=node(2) // node c has node id = 2
MATCH p=(n)-[KNOWS*]-(m),(m)-[:KNOWS]-(x)
WITH p, count(x) AS count
WHERE count>2
RETURN p

这里的技巧是分两部分指定MATCH中的路径。 然后,将第一部分用于使用WITHRETURN进行聚合。

基于Stefans的建议来研究遍历框架,我花了一段时间尝试在python(neo4j-rest-client)中弄清楚它。 现在可以使用以下代码段:

# Retrieve the node at the start of the traveral
seed_node = gdb.nodes(node_id)

# Establish what the traversal should look like
simpleTraversalTemplate = traversals.TraversalDescription().relationships('adjacent')

# Set some un-chainable attributes - work breadth first and set max depth of traversal
simpleTraversalTemplate.breadthFirst()

# This is how far you think it will go before meeting a junction. 100 is high.
simpleTraversalTemplate.max_depth(100)

# Set up a prune evaluator. This by itself (without the filter evaluator)
# returns all traversals up to the point where the link count is > 2. This includes
# the traversals to the nodes before the >2 link_count node. 
simpleTraversalTemplate.prune(value={'body':"parseInt(position.endNode().getProperty('link_count')) > 2;",
                                     'language':'javascript'})

# So, a filter is used with the prune to only return those traversals where the end node link_count 
# is >2. With only this (ie without prune), the traversal would continue and just keep returning
# those nodes with link_count > 2. 
simpleTraversalTemplate.filter(value={'body':"parseInt(position.endNode().getProperty('link_count')) > 2;",
                                     'language':'javascript'})

# Now run the traverser based on the seed node
trav = simpleTraversalTemplate.traverse(seed_node)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM