Question

Hello I am trying to create a simple neo4j DB. I have a for loop that creates a new node for every file in a directory

for(file f : files){
        Node document = graphDb.createNode();
        document.setProperty( "name", f.toString().trim());
        graphDb.getReferenceNode().createRelationshipTo(document, MatrixRelationshipTypes.REFRENCE);

that works fine. Then I am trying to create a node for each name found in a file:

                Node pName = graphDb.createNode();
                pName.setProperty("name", name.toString());
                pName.createRelationshipTo(document, MatrixRelationshipTypes.CONTAINS_NAME);

The problem is it creates a Node for every name found, which I understand is what my code is telling it to do. What I really want is for it to create a node IF one of that name doesn not already exisist. And if one of the name does exist link it to both documents it exist in.

Any ideas??

Was it helpful?

Solution

You want to use an index. There are also auto-indexes which handle the indexing (at the end of the transaction for you).

Index<Node> nameIndex = graphDb.index().forNodes("names");

public Node getOrCreateNode(String name) {
  Node found = nameIndex.get("name",name).getSingle();
  if (found!=null) return found;
  Node nameNode = graphDb.createNode();
  nameNode.setProperty("name",name);
  nameIndex.add(nameNode, "name", name);
  return nameNode;
}

You can then also query the index for nodes using wildcards (Lucene search syntax).

IndexHits<Node> nodes = nameIndex.query("name:Jo*");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top