Search code examples
python-2.7twitterneo4jtweepypy2neo

how to check if a node exists in NEO4J with py2neo


I would like to insert in my python code, a verification as follows:

{`if (data.screen_name == node.screen_name) THEN {just create new relationship with new text} else {create new node with new relationship to text } `}

i need to Implement this algorithm in my source code


Solution

  • Option 1

    Look for the node first with .find() (assuming you use neo4j 2.x with labels):

    mynode = list(graph_db.find('mylabel', property_key='screen_name',
                  property_value='foo'))
    

    Check if somethink is found:

    your_target_node = # you didn't specify where your target node comes from
    
    # node found
    if len(mynode) > 0:
        # you have at least 1 node with your property, add relationship
        # iterate if it's possible that you have more than 
        # one node with your property
    
        for the_node in mynode:
            # create relationship
            relationship = graph_db.create(
                (the_node, "LABEL", your_target_node, {"key": "value"})
            )
    
    # no node found     
    else:
        # create the node
        the_node, = graph_db.create({"key", "value"})
    
        # create relationship
        relationship = graph_db.create(
            (the_node, "LABEL", your_target_node, {"key": "value"})
        )
    

    Option 2

    Alternatively, have a look at get_or_create_path() to avoid the node lookup. But then you have to know your nodes and you need one as a py2neo Node instance. This might work if you always know/have the target node and want to create the start node:

    path = one_node_of_path.get_or_create_path(
        "rel label",   {"start node key": start node value},
    )