Search code examples
pythonneo4jpy2neo

How to get automatic node ID from py2neo?


I'm using py2neo 3.1.2 version with Neo4j 3.2.0 and I have a question about it. At Neo4J's web interface I can run the following query to get the nodes ids:

MATCH (n:Person) RETURN ID(n)

I'd like to know if there's something at py2neo API that does that same thing. I've already inspected the Node object, but I couldn't find anything about it.


Solution

  • Update: Previous Answer does not work with new py2neo but this answer works

    The current version of py2neo (4.0.0b12) dropped the remote method. Now you can get the NODE ID by accessing the py2neo.data.Node.identity attribute. It's quite simple. Let's say I query my neo4j database using py2neo like this:

    #########################
    # Standard Library Imports
    #########################
    
    import getpass
    
    #########################
    # Third party imports
    #########################
    
    import py2neo
    
    # connect to the graph
    graph = py2neo.Graph(password=getpass.getpass())
    
    # enter your cypher query to return your node
    a = graph.evaluate("MATCH (n:Person) RETURN n LIMIT 1")
    
    # access the identity attribute of the b object to get NODE ID
    node_id = a.identity
    

    We can confirm the NODE ID by querying our database using the node id returned by the attribute. If it worked correctly, a and b should be the same node. Let's do a test:

    # run a query but use previous identity attribute
    b = graph.evaluate("MATCH (n) WHERE ID(n)={} RETURN n".format(node_id))
    
    # test for equality; if we are right, this evaluates to True
    print(a == b)
    [Out]: True