はじめに
こんにちは。ponponnsanです。最近neo4jでグラフデータベースを触る機会があり、cypherクエリを作成する機会があったので、書いておきます。
Neo4j Desktop
CSVファイルから親ノードと子ノードを作成しリレーションを張る
CSVファイルはローカルの
C:\Users\user_name\.Neo4jDesktop\relate-data\dbmss\dbms-12345678\import
に入っているものとします。
LOAD CSV WITH HEADERS FROM 'file:///example.csv' AS row
WITH row
LIMIT 300
MERGE (parent:FileName {name: row.file_name, label: row.labels})
MERGE (child:path {URL: row.url, label: row.labels})
MERGE (parent)-[:PATH {path: row.path}]->(child)
python経由
def send_urls(csv_file_path):
cypher_query = """
WITH $data AS data
UNWIND data AS row
MERGE (parent:FileName {name: row.file_name, label: row.labels})
MERGE (child:path {URL: row.url, label: row.labels})
MERGE (parent)-[:PATH {path: row.path}]->(child)
"""
with open(csv_file_path, mode="r", encoding="utf-8") as file:
csv_reader = csv.DictReader(file)
with driver.session() as session:
for row in csv_reader:
print(row)
session.run(cypher_query, data=row)
ほかの役立つ記事