I'm using Cypher
to create some data in Neo4j
. It's a pretty straight forward product model, with following elements
- Product (e.g. a mobile)
- Features (e.g. quick charge)
- Related products (e.g. tampered glass)
- Outlets (e.g. local store, related products are sold through outlets)
I have written some query to insert the data. What it tries to do is
- Create a product
- Create a feature set
- Link product with feature [:HAS_FEATURES]
- Create outlets x3
- Create related product 1
- Link product to related product [:HAS_RP], and related product to all outlets [:SOLD_THROUGH]
- Create related product 2
- Link it to product & outlets like above
Below is the actual query
//Product
CREATE (p:Product {name: 'Cool Mobile YX Plus',
key: 'MOB0001',
version: 'X.1'
}),
//Features
(f:Features {hasQuickCharge: true,
isAvailable: true,
hasVolte: false
})
MERGE (p) -[:HAS_FEATURES]-> (f)
//Outlets (:Product level lookup)
CREATE (o1:Outlet {productType: 'New', seller: 'National_Shops', prId: 'MOB0001'})
CREATE (o2:Outlet {productType: 'New', seller: 'Local_Shops', prId: 'MOB0001'})
CREATE (o3:Outlet {productType: 'New', seller: 'Online_Shops', prId: 'MOB0001'})
//Related products
CREATE (rps1:RPS {rpId: 'TGS1108',
rpName: 'YX Plus Tampered Glass',
price: 180.99
})
WITH rps1
MATCH (ol1:Outlet {productType: 'New', prId: 'MOB0001'})
MATCH (pr1:Product {key: 'MOB0001'})
MERGE (pr1) -[:HAS_RP {typeName: 'Child'}]-> (rps1)
MERGE (rps1) -[:SOLD_THROUGH]-> (ol1)
CREATE (rps2:RPS {rpId: 'CVR0204',
rpName: 'YX Plus back cover',
price: 299.00
})
WITH rps2
MATCH (ol2:Outlet {productType: 'New', prId: 'MOB0001'})
MATCH (pr2:Product {key: 'MOB0001'})
MERGE (pr2) -[:HAS_RP {typeName: 'ChargeFor'}]-> (rps2)
MERGE (rps2) -[:SOLD_THROUGH]-> (ol2)
Now the problem is, the second related product is created 3 times, where it was expected to be created only once, just like the first related product.
Can anyone please help me understand what I'm doing wrong? Also, any help in writing the query in better way would be great.
The issue is located here :
MATCH (ol1:Outlet {productType: 'New', prId: 'MOB0001'})
You created before 3 nodes that comply to the criteria of the MATCH :
CREATE (o1:Outlet {productType: 'New', seller: 'National_Shops', prId: 'MOB0001'}) CREATE (o2:Outlet {productType: 'New', seller: 'Local_Shops', prId: 'MOB0001'}) CREATE (o3:Outlet {productType: 'New', seller: 'Online_Shops', prId: 'MOB0001'})
So,
MATCH (ol1:Outlet {productType: 'New', prId: 'MOB0001'})
will return 3 rows, and for each row, it will execute the next part of the query, 3 times this part :