问题
I have node PRODUCT with multiple REVIEW node. I would create node PRODUCE if the product is not exist, then bind with REVIEW.
For the example, I want a PRODUCE node {name:'X phone'} with 3 REVIEW {content:'best phone ever'}, {content:'worst phone ever'}, {content:'nope'}.
I tried
First, use one cypher MERGE for each REVIEW.
MERGE(product:PRODUCT{name:'X phone'})-[:RATE]-(review:REVIEW{content:'best phone ever'})
MERGE(product:PRODUCT{name:'X phone'})-[:RATE]-(review:REVIEW{content:'worst phone ever'})
MERGE(product:PRODUCT{name:'X phone'})-[:RATE]-(review:REVIEW{content:'nope'})
It did not work and will create 3 PRODUCT {name:'X phone'}
I tried to use MERGE to create/reuse the PRODUCT, them MATCH + MERGE the review. (2 cypher for each review)
// create/reuse PRODUCT
MERGE(product:PRODUCT{name:'X phone'})
// create/reuse review
MATCH (product:PRODUCT{name:'X phone'}) MERGE (product)-[:RATE]-(review:REVIEW{content:'nope'})
// create/reuse PRODUCT
MERGE(product:PRODUCT{name:'X phone'})
// create/reuse review
MATCH (product:PRODUCT{name:'X phone'}) MERGE (product)-[:RATE]-(review:REVIEW{content:'best phone ever'})
// create/reuse PRODUCT
MERGE(product:PRODUCT{name:'X phone'})
// create/reuse review
MATCH (product:PRODUCT{name:'X phone'}) MERGE (product)-[:RATE]-(review:REVIEW{content:'worst phone ever'})
Second solution worked, it only create 1 PRODUCT and connect 3 REVIEW to that PRODUCT. But, I have to use as twice as number of cypher.
I would like to ask if there is any better way for my problem ?
SOLUTION
I did not know that I can chain MERGE with MERGE
thank to @Mạnh Quyết Nguyễn answer, I can do 1 cypher per review sample that chain 2 MERGE clause. First MERGE create a product if not exist, second MERGE create review if not exist.
MERGE (product:PRODUCT{name:'X phone'}) MERGE (product)-[:RATE]-(review:REVIEW{content:'worst phone ever'})
回答1:
Your subsequent match/merge is redundant. You can do:
// create/reuse PRODUCT
MERGE (product:PRODUCT {name:'X phone'})
MERGE (product)-[:RATE]-(:REVIEW {content:'nope'})
MERGE (product)-[:RATE]-(:REVIEW {content:'best phone ever'})
MERGE (product)-[:RATE]-(:REVIEW {content:'worst phone ever'})
来源:https://stackoverflow.com/questions/51738618/how-to-use-merge-to-create-or-reuse-a-part-of-pattern