Search code examples
pythonpython-3.xneo4jpy2neo

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


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

What I have: a node from the graph 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 aA neo4j return describing how these relationships are connected to node a (in this case, 7)

What I've tried:

x = relMatch.get(20943820943) using one of the IDs of the relationships to see what's what. It returns None, which the docs say means

If no such Relationship is found, py:const:None is returned instead. Contrast with matcher[1234] which raises a KeyError if no entity is found.

which leaves me thinking I'm coming at it all wrong.

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

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

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?


Solution

  • With a RelationshipMatcher, you can simply take a count using 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))

    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. Using len simply evaluates the match and returns a count.