How to create nodes and relationships from csv in neo4j

一世执手 提交于 2020-03-12 05:59:57

问题


I am loading a csv file with cypher query. The csv file is having 4 columns. 2 for columns and 2 for tables as shown below.

I want to create 2 types of nodes database and tables from those 4 columns. How can I create unique nodes for database and columns and to have relationships between them?

As per logisima's answer I added below query to create nodes for database and columns and added relationships. But there is some duplication in nodes.

        `LOAD CSV WITH HEADERS FROM 'file:///test1.csv' AS row
        MERGE (source:Database { source: row.Source_DB})
        MERGE (target:Database { target: row.Target_DB})
        MERGE (source_table:Table { source_table: row.Source_Table})
        MERGE (target_table:Table { source_table: row.Target_Table})
        MERGE (source)-[:LINKED_TO]-> (target)
        MERGE (source)-[:LINKED_TO]-> (source_table)
        MERGE (source)-[:LINKED_TO]-> (target_table)
        MERGE (target)-[:LINKED_TO]-> (target_table)`

Please bear with me I'm new to Neo4j.


回答1:


Something like that ?

LOAD CSV WITH HEADERS FROM 'file:///MASTER.csv' AS row

MERGE (source:Database { db: row.Source_DB, table: row.Source_Table})
MERGE (target:Database { db: row.Target_DB, table: row.Target_Table})
MERGE (source)-[:LINKED_TO]->(target)

Update for the comment

CREATE CONSTRAINT ON (n:Database) ASSERT n.db IS UNIQUE;
CREATE CONSTRAINT ON (n:Table) ASSERT n.id IS UNIQUE;

LOAD CSV WITH HEADERS FROM 'file:///MASTER.csv' AS row

MERGE (sourceDb:Database { db: row.Source_DB})
MERGE (sourceTable:Table { id: row.Source_DB + "-" + row.Source_Table, table: row.Source_Table})
MERGE (sourceDb)-[:HAS_TABLE]->(sourceTable)

MERGE (targetDb:Database { db: row.Target_DB})
MERGE (targetTable:Table { id: row.Target_DB + "-" + row.Target_Table, table: row.Target_Table})
MERGE (targetDb)-[:HAS_TABLE]->(targetTable)

MERGE (sourceTable)-[:LINKED_TO]->(targetTable);



回答2:


Your query needs to create Database nodes with a consistent property for the name of the DB. You are using 2 different property names, so you are creating 2 nodes sometimes for the same DB.

Instead of:

MERGE (source:Database { source: row.Source_DB})
MERGE (target:Database { target: row.Target_DB})

use something like:

MERGE (source:Database {name: row.Source_DB})
MERGE (target:Database {name: row.Target_DB})

You will also have to fix the rest of the query to use that property name.



来源:https://stackoverflow.com/questions/60560218/how-to-create-nodes-and-relationships-from-csv-in-neo4j

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!