Question

I want to insert data from a text file into Neo4j using py2neo.But is their a way to check before creating node that it already exist.Is their any py2neo way for CREATE UNIQUE For example

create node A to B create node A to C

Then only single node A must be created and connected to B and C

insert_data.py

from pprint import pprint
from py2neo import neo4j,node, rel, cypher
#------------------------------------------------------------------------------ 

f = open('sample_dataset')
lines = f.readlines()
graph_db = neo4j.GraphDatabaseService()
print graph_db.get_reference_node()
try:
    for row in lines:    
        from_node = row.split('\t')[0].strip()
        to_node = row.split('\t')[1].strip()
        graph_db.create(
                        node(name=from_node),
                        node(name=to_node))                               
except Exception as e:
    print e

data.txt:

101 102
101 104
101 107
101 125
101 165
101 168
101 170
101 176
101 180
101 181
101 182
101 209
101 210
101 248
101 306
101 329
101 330
101 340
101 349
101 352
101 355
101 356
101 359
101 364
101 365
101 368
101 372
101 373
101 383
101 433
101 438
101 439
101 441
101 448
101 466
101 471
101 484
101 526
Was it helpful?

Solution 2

There are several ways to manage uniqueness through py2neo and CREATE UNIQUE is supported both through direct Cypher queries and through several wrapper methods. I recently wrote a blog post on just this topic so you can probably get some pointers from here:

http://blog.safaribooksonline.com/2013/08/07/managing-uniqueness-with-py2neo/

Hope this helps.

OTHER TIPS

One way of doing this is with CYPHER 2.0 and py2neo. In your code simply replace

graph_db.create

with this, where the start of the query string says CYPHER 2.0, which has support for MERGE:

query = neo4j.CypherQuery(graph_db,
        """CYPHER 2.0 
            merge (n {name: {from}})
            merge(m {name: {to}}) 
            create unique (n)-[:relation]->(m)""")
result = query.execute( from = from_node, to = to_no)

With merge n, n will only be created if it is not in the database. Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top