简体   繁体   English

使用py2neo将文本数据插入Neo4j

[英]Insert text data into Neo4j using py2neo

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 我想从一个文本文件中的数据插入到Neo4j使用py2neo.But是他们的方式创造,它已经exist.Is他们的任何py2neo路节点之前检查CREATE UNIQUE例如

create node A to B create node A to C 创建节点A到B创建节点A到C

Then only single node A must be created and connected to B and C 然后,仅必须创建单个节点A并将其连接到B和C

insert_data.py 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: 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

One way of doing this is with CYPHER 2.0 and py2neo. 一种实现方法是使用CYPHER 2.0和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: 与此相关,查询字符串的开头表示CYPHER 2.0,它支持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. 通过合并n,仅当n不在数据库中时才会创建n。 Hope this helps. 希望这可以帮助。

There are several ways to manage uniqueness through py2neo and CREATE UNIQUE is supported both through direct Cypher queries and through several wrapper methods. 有多种方法可以通过py2neo管理唯一性,并且通过直接Cypher查询和几种包装器方法都支持CREATE UNIQUE。 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/ http://blog.safaribooksonline.com/2013/08/07/managing-uniqueness-with-py2neo/

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM