javaloopsneo4jgraph-databasesneo4j-java-api

How to automate Node naming in neo4j using loop?


I have list of String and i want to import all the elements to the graph database. By saying import i mean, i want to set the String as the Node's property. The size of the list is gonna be massive. So is there any way to automate Node naming ? Because by the traditional way, you have to create Nodes by calling graphDb.createNode() 100 times, if the size of the list is 100.


Solution

  • You can pass your list of strings as a parameter to a Cypher query. Here is a sample snippet:

    List<String> names = ...;
    try ( Transaction tx = graphDb.beginTx() )
    {
        String queryString = "UNWIND {names} AS name CREATE (n:User {name: name})";
        Map<String, Object> parameters = new HashMap<>();
        parameters.put( "names", names );
        graphDb.execute( queryString, parameters );
        tx.success();
    }
    

    Note: If the list of strings is "too long", the above approach will not work, as the server could run out of memory trying to do all that processing in a single transaction. In that case, you may want to use an APOC procedure like apoc.periodic.iterate to create the nodes in smaller batches.