Reputation: 11
I have a table with two fields: product and parent product.
The data is similar to this
Prod Parent
A A1
A1 B1
B A1
B1 C
How to create a graph where I tie in the product to its parent so that I can query all levels? E.g if I query on A, I need to know about its parent A1, grandparent B1 and one level higher C. I need to be able to traverse any which way, but how do I create the node and relationship to do recursive looks.
Upvotes: 1
Views: 549
Reputation: 8556
The Datamodel
Given your description and the sample data, your graph looks something like this:
Creating the graph
Given a CSV file with the contents:
"Prod","Parent"
"A","A1"
"A1","B1"
"B","A1"
"B1","C"
You can create this graph in Neo4j using LOAD CSV
Cypher statement:
LOAD CSV WITH HEADERS FROM 'file:///path/to/file.csv' AS row
MERGE (prod:Product {name: row.Prod})
MERGE (parent:Product {name: row.Parent)
CREATE UNIQUE (parent)-[:IS_PARENT_OF]->(prod)
Querying the graph
Find the parents of product A1:
MATCH (p:Product {name: "A1"})<-[:IS_PARENT_OF]-(parent:Product)
RETURN parent
Find all ancestors (arbitrary depth) of A1:
MATCH (p:Product {name: "A1"})<-[:IS_PARENT_OF*1..15]-(a:Product)
RETURN a
Upvotes: 1