To create nodes for each row in CSV file and relationships for sub items

I want to create a node for each row in CSV file and to create relationships for sub-items. Like

CREATE (p1:Person{pid:1,name:"P1"})
CREATE (p1a:Person{pid:1a,name:"P1a"})
CREATE (p1b:Person{pid:1b,name:"P1b"})
CREATE (p2:Person{pid:2,name:"P2"})

And Relationships: (p1)-[:KNOWS]->(p1a),(p1)-[:KNOWS]->(p1b),(p2)-[:KNOWS]->(p2a), (p2)-[:KNOWS]->(p2b),(p2)-[:KNOWS]->(p2c) , etc.

But want to do it using an automatic way.

LOAD CSV WITH HEADERS FROM 'file:///test.csv' as row
CREATE (p:Person{pid:toInteger(,})

I am unable to create different nodes for each row and not sure how to create Relationships exactly only 2 times for p1 and 3 times for p2 and 1 time for p3. Could you please help me to write a Cypher query. Sample CSV here.

pid name
1 P1
1.1 P1a
1.2 P1b
2 P2
2.1 P2a
2.2 P2b
2.3 P2c
3 P3
3.1 P3a
4 P4
4.1 P4a
4.2 P4b
4.3 P4c
4.4 P4d
5 P5

Hey naikum,
This is some pseudocode that may get you started:

for i from 1 to n
  match node1 where name = "P" + str i 
  match node2 where name starts with "P" + str i and size > 2
  create node1-[:knows]->node2

It is hacky, though.

If possible, reformat your CSV such that it specifies parent and child relationships, something like this:

pid parent, child
1 null P1
1.1 P1 P1a
1.2 P1 P1b
2 null P2

That way you can CREATE the child, filter out rows where the parent is null, then MERGE the parent, then MERGE the relationship:

LOAD CSV WITH HEADERS FROM 'file:///test.csv' as row
CREATE (child:Person {pid:toInteger(,name:row.child})
WITH row, child
WHERE row.parent IS NOT NULL
MATCH (parent:Person {name:row.parent})
MERGE (parent)-[:KNOWS]->(child)

This assumes the ordering of the CSV is such where parent nodes are always created before their children.

Thanks, it is working.