cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

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

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:

2X_4_4e9552ab5068aabde1177cb2f3d55ba817f74c2e.jpeg

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.

1 ACCEPTED SOLUTION

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)

View solution in original post

1 REPLY 1

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)