Build Neo4J Graph from Json in Spring

373 views Asked by At

I'm wondering what is the best way to create a graph in Neo4j from json using Spring. Imagine I have a simple NodeEntity Person:

@NodeEntity public class Person {
  private Set<Person> friends;
}

I want to build up the graph of friendships between persons from a json object like:

{
  persons: [
    {name:"Fritz", friend:["Hans"]},
    {name:"Hans", friends:["Fritz", "Georg"]},
    {name:"Georg", friends:["Hans"]}
  ]
}

Can I use the Spring Data Rest APIs to de-serialize the json directly to node entities and relations?

1

There are 1 answers

1
Michael Hunger On

Good question, in the past I only tried to write to SD-REST for single entities, not entities with relationships.

I would probably write my own rest-controller and transform the JSON into the correct objects.

You could also use Cypher directly and pass the json root as parameter json to cypher.

UNWIND {json}.persons as person
// MERGE = get-or-create
MERGE (p:Person {name:person.name})
UNWIND person.friends as friend
// because the friend can come earlier as friend than as a person
MERGE (f:Person {name:friend.name})
// merge on relationship to make sure it only exists once, no matter the direction
MERGE (p)-[:KNOWS]-(f)

This query could be part of an SDN repository or be called via Neo4jTemplate or -Session.

In SDN4 you can use that created that directly from your domain objects.