简体   繁体   English

如何使用py2neo计算与一种节点的关系(一种类型)

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

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

What I have: a node from the graph a 我所拥有的:图中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)

What I want: the count of how many "CREATED" relationships are connected to a 我想要的是:与a "CREATED"关系连接a neo4j返回,描述如何将这些关系连接到节点a (in this case, 7) (在这种情况下,为7)

What I've tried: 我尝试过的

x = relMatch.get(20943820943) using one of the IDs of the relationships to see what's what. x = relMatch.get(20943820943)使用关系的ID之一查看内容。 It returns None , which the docs say means 它返回None文档说这意味着

If no such Relationship is found, py:const:None is returned instead. 如果找不到这样的关系,则返回py:const:None。 Contrast with matcher[1234] which raises a KeyError if no entity is found. 如果未找到任何实体,则与matcher [1234]进行对比,后者会引发KeyError。

which leaves me thinking I'm coming at it all wrong. 这让我以为我错了。

also: relMatch.match(a,"CREATED") which raises 还: relMatch.match(a,"CREATED")引发

raise ValueError("Nodes must be supplied as a Sequence or a Set") 引发ValueError(“节点必须作为序列或集合提供”)

telling me that I'm definitely not reading the docs right. 告诉我我绝对不是在阅读正确的文档。

Not necessarily using this class, which probably isn't what I think it is, how do I get a count of how many ["CREATED"] are pointed at a ? 不一定使用这个类,我可能不是这个类,我如何计算指向a ["CREATED"]数量?

Below works, and is easier to write than the previous implementation, but I don't think it's the right way to do it. 下面的作品,并且比以前的实现更容易编写,但是我认为这不是正确的方法。

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

With a RelationshipMatcher , you can simply take a count using len . 使用RelationshipMatcher ,您可以简单地使用len进行计数。 So if I read your code correctly, you'll need something like: 因此,如果我正确阅读了您的代码,则将需要以下内容:

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

Or even easier: 甚至更简单:

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

(since graph.match is a shortcut to RelationshipMatcher(graph) ) (因为graph.matchRelationshipMatcher(graph)的快捷方式)

The (None, a) tuple specifies an ordered pair of nodes (relationships in one direction only) where the start node is any node and the end node is a . (None, a)元组指定节点的有序对(仅在一个方向上的关系),其中开始节点是任何节点,结束节点是a Using len simply evaluates the match and returns a count. 使用len只是评估匹配并返回一个计数。

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

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