如何在Transactional Cypher参数内实现关系属性数值累加?
Hey Alex, let's get your problem sorted out—you've got two main issues here: invalid JSON syntax and incorrect Cypher logic for incrementing a relationship property. Let's break it down step by step:
1. Fix the Invalid JSON Payload
Your current payload throws the "invalid JSON" error because of the unnecessary + sign before 144 in your parameters. JSON doesn't allow leading plus signs for numeric values. Even if you fixed this, though, your original Cypher would still overwrite the PROX property instead of accumulating it—so let's tackle the real goal next.
2. Correct Cypher for Numeric Accumulation
To increment a relationship's numeric property, you need to perform the addition directly in the Cypher statement (not pass a precomputed value via parameters unless you calculate it externally). Here's the adjusted, working request:
Working Transactional Cypher Request
:POST /db/data/transaction/commit { "statements": [ { "statement": "MATCH (r:CONCEPT {EX: $Example})-[proximity:FLIGHT]->(s:NARRATION {CARD_EX: $Example2}) SET proximity.PROX = proximity.PROX + $addValue;", "parameters": { "Example": "Example", "Example2": "Example2", "addValue": 144 } } ] }
Key Changes Explained:
- Instead of replacing the entire
proximityrelationship (which is whatSET proximity = {prop}was doing), we target the specificPROXproperty withproximity.PROX. - We use
proximity.PROX + $addValueto increment the existing value by your parameterized number—this is the core logic for accumulation. - Clean parameter naming (
addValue) makes the intent of the parameter clear at a glance.
Handling Missing PROX Properties
If there's a chance the PROX property doesn't exist on the relationship yet (which would cause a null error when adding), use COALESCE to default to 0:
SET proximity.PROX = COALESCE(proximity.PROX, 0) + $addValue;
This ensures that if PROX is missing, it starts at 0 before adding your addValue.
Why Your Original Approach Didn't Work
Your original SET proximity = {prop} was trying to replace the entire relationship object with the properties in {prop}, which is not what you want when you just need to update one property. By targeting the specific property and performing the addition in Cypher, you achieve the accumulation behavior you're after.
内容的提问来源于stack exchange,提问作者Houngan34

