Sohail Ahmed
Sohail Ahmed

Reputation: 1667

Create relation with existing nodes Cypher Neo4j

I am creating a relationship graph with unique Source's hashtag. I am wondering that is every time I have to check if source or target is already exists after creating nodes first time?

If I use Merge when source is exists but target is new then merge failed to create node. I want to create following graph.

I am using following code using JAVA

    String CQL = "CREATE (source:Source {hashtag: '1'})-[:TIMELINE {weight: 3, date: '1417132800'}]->(target:Target {hashtag: '2'})";
    ExecutionEngine execEngine = new ExecutionEngine(graphDb, StringLogger.DEV_NULL);
    ExecutionResult execResult = execEngine.execute(CQL);
    String results = execResult.dumpToString();
    System.out.println(results);

Secondly please guide me how can I get json from ExecutionResult execResult = execEngine.execute(CQL); to create map in d3.js

Following CQLs I have to run.

    CREATE CONSTRAINT ON (label:Source) ASSERT label.hashtag IS UNIQUE

    // if source and target are new
    CREATE (source:Source {hashtag: '1'})-[:TIMELINE {weight: 3, date: "1417132800"}]->(target:Target {hashtag: '2'})

    // if source and target are already created and have another TIMELINE relation
    MATCH (source:Source {hashtag: '1'}),(target:Target {hashtag: '2'}) CREATE (source)-[:TIMELINE {weight: 15, date: "1417132200"}]->(target)

    // if source already exists but target is new
    MATCH (source:Source {hashtag: '1'}) CREATE (source)-[:TIMELINE {weight: 20, date: "1417133200"}]->(target:Target {hashtag: '3'})

    // if source is new but target already exists
    MATCH (target:Target {hashtag: '2'}) CREATE (target)<-[:TIMELINE {weight: 30, date: "1417133400"}]-(source:Source {hashtag: '4'})

Upvotes: 0

Views: 489

Answers (1)

Stefan Armbruster
Stefan Armbruster

Reputation: 39915

Don't quite understand what you mean with

f I use Merge when source is exists but target is new then merge failed to create node.

MERGE should be used in a minimalistic way. In case a single item of a path specified in MERGE is not found, the whole pattern is created. That said, if you want to eventually create start node, end node and a relationship in between use

MERGE (source:Source{hashtag:'1'})
MERGE (target:Source{hashtag:'3'})
MERGE (source)-[:TIMELINE {weight: 30, date: "1417133400"}]->(target)

regarding your 2nd question: creating JSON

If you switch over your usage model to run a Neo4j server and use the transactional Cypher endpoint, you get back JSON directly.

If you want to render JSON directly from Java code, use the usual suspects, e.g. Google's GSON.

Upvotes: 1

Related Questions