簡體   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