[英]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
(在这种情况下,为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.match
是RelationshipMatcher(graph)
的快捷方式)
(None, a)
元组指定节点的有序对(仅在一个方向上的关系),其中开始节点是任何节点,结束节点是a
。 使用len
只是评估匹配并返回一个计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.