簡體   English   中英

如何使用py2neo計算與一種節點的關系(一種類型)

[英]How to count relationships (of one type) to a node using py2neo

使用py2neo 4.x,neo4j 3.5.3,python 3.7.x

我所擁有的:圖中a一個節點

graph = Graph(
    host="alpha.graph.domain.co",
    auth=('neo4j', 'theActualPassword')
)
# grab the graph
a = Node("Type", url="https://en.wikipedia.org/wiki/Vivendi")
# create a local node with attributes I should be able to MERGE on
graph.merge(a,"Type","url")
# do said merge
graph.pull(a)
# pull any attributes (in my case Labels) that exist on the node in neo4j...
# ...but not on my local node
# better ways to do this also would be nice in the comments
relMatch = RelationshipMatcher(graph)

我想要的是:與a "CREATED"關系連接a neo4j返回,描述如何將這些關系連接到節點a (在這種情況下,為7)

我嘗試過的

x = relMatch.get(20943820943)使用關系的ID之一查看內容。 它返回None文檔說這意味着

如果找不到這樣的關系,則返回py:const:None。 如果未找到任何實體,則與matcher [1234]進行對比,后者會引發KeyError。

這讓我以為我錯了。

還: relMatch.match(a,"CREATED")引發

引發ValueError(“節點必須作為序列或集合提供”)

告訴我我絕對不是在閱讀正確的文檔。

不一定使用這個類,我可能不是這個類,我如何計算指向a ["CREATED"]數量?

下面的作品,並且比以前的實現更容易編寫,但是我認為這不是正確的方法。

result = graph.run(
    "MATCH(a) < -[r:CREATED]-(b) WHERE ID(a)=" + str(a.identity) + " RETURN count(r)"
).evaluate()
print(result)

使用RelationshipMatcher ,您可以簡單地使用len進行計數。 因此,如果我正確閱讀了您的代碼,則將需要以下內容:

count = len(RelationshipMatcher(graph).match((None, a), "CREATED"))

甚至更簡單:

count = len(graph.match((None, a), "CREATED"))

(因為graph.matchRelationshipMatcher(graph)的快捷方式)

(None, a)元組指定節點的有序對(僅在一個方向上的關系),其中開始節點是任何節點,結束節點是a 使用len只是評估匹配並返回一個計數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM