UNWIND multiple unrelated arrays loaded from JSON

2020-07-18 07:44发布

问题:

I'm trying to UNWIND multiple array properties with a single call to apoc.load.json(). The version I have doesn't fully work: some relationships don't get loaded. My guess is that it's due to the piping of output via the WITH command. I can have it all load if I run the unwinds separately for each array-based property, but I'm curious as to how it can be done all together.

Any insights and pointers are appreciated =)

//LOAD CLASSES AND UNWIND COMMON ITEMS,COMPANIONS,LOCATIONS 
CALL apoc.load.json("file:///c://pathToFile//classes.json") YIELD value AS class
MERGE (c:Class {name: class.name})
SET 
c.strength = class.strength,
c.intelligence = class.intelligence,
c.dexterity = class.dexterity,

WITH c, class.items AS items, class.companions AS companions, class.locations AS locations
UNWIND items AS item
UNWIND companions AS companion
UNWIND locations AS location

MERGE (i:Item {name: item})
MERGE (i)-[:LIKELY_HAS]->(c)
MERGE (c)-[:LIKELY_BELONGS_TO]->(i)

MERGE (comp:Class {name: companion})
MERGE (comp)-[:LIKELY_COMPANION_OF]->(c)
MERGE (c)-[:LIKELY_ACCOMPANIED_BY]->(comp)

MERGE (l:Location {name: location})
MERGE (l)-[:LIKELY_LOCATION_OF]->(c)
MERGE (c)-[:LIKELY_LOCATED_IN]->(l)

Example entry in the JSON file:

 {
    "name": "KNIGHT",
    "strength": [75,100],
    "intelligence": [40,80],
    "dexterity": [40,85],
    "items": [
        "SWORD",
        "SHIELD"
    ],
    "companions":[
        "KNIGHT",
        "SERVANT",
        "STEED"
    ],
    "locations": [
        "CASTLE",
        "VILLAGE",
        "CITY"
    ]
}

回答1:

The actual problem here is just an unnecessary , between the last line of your SET clause and the WITH clause. Get rid of that, and you get rid of the syntax error.

That said, I highly recommend grouping each UNWIND with the clauses which act on the unwinded values, then resetting the cardinality back to a single row before performing the next UNWIND and processing. Something like this:

//LOAD CLASSES AND UNWIND COMMON ITEMS,COMPANIONS,LOCATIONS 
CALL apoc.load.json("file:///c://pathToFile//classes.json") YIELD value AS class
MERGE (c:Class {name: class.name})
SET 
c.strength = class.strength,
c.intelligence = class.intelligence,
c.dexterity = class.dexterity

WITH c, class

UNWIND class.items AS item
MERGE (i:Item {name: item})
MERGE (i)-[:LIKELY_HAS]->(c)
MERGE (c)-[:LIKELY_BELONGS_TO]->(i)

WITH distinct c, class
UNWIND class.companions AS companion
MERGE (comp:Class {name: companion})
MERGE (comp)-[:LIKELY_COMPANION_OF]->(c)
MERGE (c)-[:LIKELY_ACCOMPANIED_BY]->(comp)

WITH distinct c, class
UNWIND class.locations AS location
MERGE (l:Location {name: location})
MERGE (l)-[:LIKELY_LOCATION_OF]->(c)
MERGE (c)-[:LIKELY_LOCATED_IN]->(l)