Creating nodes from nested JSON using apoc.load.json() procedure


(Adnan904) #1

I have the following JSON file "test.json":

{
    "Environment": {

        "Environment_elements": [{
                "name": "weather",
                "id": "1",
            },

            {
                "name": "enemy",
                "id": "2",
            },

            {
                "name": "external_operator",
                "id": "3",
            }
        ],

        "System_element": {
            "name": "weapons_system",
            "id": "4",
            },

        "Connections": [{
                "name": "weather_connection",
                "id": "4",
                "source": "1",
                "target": "4",
            },

            {
                "name": "enemy_location_connection",
                "id": "5",
                "source": "2",
                "target": "4",
            },

            {
                "name": "external_operator_connection",
                "id": "6",
                "source": "3",
                "target": "4",
            }
        ]



    }
}

I want to create a graph like this:

graph

After reading the Json using the apoc.load.json(URL) procedure , what query do I write to get the graph as in the picture? I am having problems understanding how to UNWIND the nested objects.


(Mark Needham) #2

You can use a combination of UNWIND and FOREACH to do what you want:

call apoc.load.json("file:///tmp/test.json")
YIELD value
FOREACH (node in value.Environment.Environment_elements +  [value.Environment.System_element] |
  MERGE (e:Element {id: node.id})
  SET e.name = node.name
)
WITH value
UNWIND value.Environment.Connections AS connection
MERGE (e1:Element {id: connection.source})
MERGE (e2:Element {id: connection.target})
MERGE (e1)-[:CONNECTED]->(e2)