【问题标题】:How to count relationships (of one type) to a node using py2neo如何使用 py2neo 计算与节点的关系(一种类型)
【发布时间】:2019-03-16 13:15:28
【问题描述】:

使用 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)

我想要什么:有多少 "CREATED" 关系连接到 a(在本例中为 7)

我尝试过的:

x = relMatch.get(20943820943) 使用关系的 ID 之一来查看是什么。它返回Nonedocs 的意思是

如果没有找到这样的关系,则返回 py:const:None。与 matcher[1234] 对比,如果没有找到实体则会引发 KeyError。

这让我觉得我完全错了。

还有:relMatch.match(a,"CREATED") 这引发了

raise ValueError("Nodes must be provided as a Sequence or a Set")

告诉我我肯定没有正确阅读文档。

不一定要使用这个类,这可能不是我想的那样,我如何计算有多少["CREATED"] 指向a

【问题讨论】:

    标签: python python-3.x neo4j py2neo


    【解决方案1】:

    使用RelationshipMatcher,您可以使用len 简单地进行计数。因此,如果我正确阅读了您的代码,您将需要以下内容:

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

    甚至更简单:

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

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

    (None, a) 元组指定一对有序节点(仅在一个方向上的关系),其中起始节点是任意节点,结束节点是 a。使用len 只计算匹配并返回一个计数。

    【讨论】:

    • 奈杰尔,你才是真正的MVP
    【解决方案2】:

    下面的工作,并且比以前的实现更容易编写,但我认为这不是正确的方法。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多