Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neo4j check if node exists before creating?

Tags:

java

neo4j

I have a feeling I'm going about this all wrong. But anyway.

I have an sql database which has essentially a purposefully denormalised table which I've constructed to make this task easier for me, so I can just grab stuff from one table.

What I have is a table of pairs, something like this:

user_lo | user_hi | something_else | other stuff
1000    | 1234    | 1231251654     | 123
1050    | 1100    | 1564654        | 45648
1080    | 1234    | 456444894648   | 1

And so on.

So for my neo4j graph db, I want each user id as a node, the other stuff isn't too important but will be the stuff in the relations basically.

I only want one node for each user, so my feeling is that if I do something like this:

while (rs.next()) {
    node_lo = db.createNode();
    node_lo.setProperty("user_id", rs.getInt(1));
    node_hi = db.createNode();
    node_hi.setProperty("user_id", rs.getInt(2));
}

That when we add the node with user_id 1234 for the second time, it will just create a new node, but I what I want is for it to just grab this node instead of creating it so I can add it to the relationship to 1080 in this case.

So what is the way to do this?

like image 347
Tom Carrick Avatar asked Jun 12 '12 15:06

Tom Carrick


2 Answers

Have you looked at CREATE UNIQUE?

If you can't use Cypher, maybe you can use unique nodes?

like image 187
Andres Avatar answered Sep 24 '22 01:09

Andres


Use an index to search, and if no result of found, create a new one.

Index<Node> userIndex = graphDatabaseService.index().forNodes('UserNodes');

IndexHits<Node> userNodes = userIndex.get('id', 1234);

if(!userNodes.hasNext()){
    //Create new User node
} else {
    Node userNode = userNodes.next();
}

Is this the type of operation you are looking for?

like image 36
Nicholas Avatar answered Sep 23 '22 01:09

Nicholas