Trouble with correctly modeling data in Neo4j / Cypher

Viewed 18

I am a beginner with Neo4j/Cypher and I'm having trouble modeling my data correctly.

The Data has following relationship:

MANUFACTURER_A (unique) -> PRODUCT_A (unique just withing MANUFACTURER_A) -> CUSTOMER_A (globally unique)
MANUFACTURER_A (unique) -> PRODUCT_A (unique just withing MANUFACTURER_A) -> CUSTOMER_B (globally unique) 
MANUFACTURER_B (unique) -> PRODUCT_A (unique just withing MANUFACTURER_B) -> CUSTOMER_A (globally unique)

I am not able to make Product_A unique within a Manufacturer. I always get one line from Manufacturer_A to Product_A and another one from Manufacturer_B but I actually want two Product_A nodes (one from each Manufacturer), but just one Product_A node per Manufacturer.

I tried the following:

CREATE CONSTRAINT ON (c:MANUFACTURER) ASSERT c.MANUFACTURER IS UNIQUE;
CREATE CONSTRAINT ON (c:CUSTOMER) ASSERT c.CUSTOMER IS UNIQUE;

LOAD CSV WITH HEADERS FROM
'file:///small.csv' AS line

WITH line LIMIT 20
MERGE (CUSTOMER:Customer {Name: line.CUSTOMER})
MERGE (MANUFACTURER:Manufacturer {Name:line.MANUFACTURER})
MERGE (PRODUCT:Product {Name: line.PRODUCT})

MERGE (MANUFACTURER)<-[:PRODUCES]-(PRODUCT)
MERGE (CUSTOMER)<-[:CONSUMES]-(PRODUCT)

;

How would I model that correctly?

1 Answers

In this case, you don't want to MERGE the :PRODUCT node alone, but as part of a pattern connected to your merged manufacturer variable, that provides the context that the pattern you are looking for must be connected, and if no such pattern exists, the non-bound parts will be created.

...
MERGE (MANUFACTURER:Manufacturer {Name:line.MANUFACTURER})
MERGE (MANUFACTURER)<-[:PRODUCES]-(PRODUCT:Product {Name: line.PRODUCT})
...

So it won't matter if a product of that name exists elsewhere in the graph, as long as one isn't found connected to that manufacturer, it will be created as part of the MERGE.

This knowledge base article may be helpful as well, as it covers this application and more:

https://neo4j.com/developer/kb/understanding-how-merge-works/

Related