How to load CSV file with cypher in java?

2019-03-01 20:17发布

I am new to cypher. I want to load a csv using cypher in java. I googled and found the following piece

LOAD CSV WITH HEADERS FROM "http://neo4j.com/docs/2.3.1/csv/import/movies.csv" AS csvLine
MERGE (country:Country { name: csvLine.country })
.....

How to use this load csv query into java code. I tried something like this.

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import javax.naming.spi.DirStateFactory.Result;

import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.cypher.javacompat.ExecutionResult;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.kernel.impl.util.FileUtils;
public class test_new {


private static final String DB_PATH = "C:...../default.graphdb";
public static void main( final String[] args ) throws IOException
{
    GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );



    Transaction tx1 = db.beginTx();
    try{

        ExecutionEngine engine = new ExecutionEngine(db);
      ExecutionResult result = engine.execute("LOAD CSV WITH HEADERS FROM "C:/..../Mock_data.csv" AS csvLine ");

        tx1.success();
    } finally {
        tx1.close();

    }
    db.shutdown();
}

}

But I am not sure about this line.

 ExecutionResult result = engine.execute("LOAD CSV WITH HEADERS FROM "C:/..../Mock_data.csv" AS csvLine ");

It throws syntax error.

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
Syntax error, insert ")" to complete MethodInvocation
Syntax error, insert ";" to complete LocalVariableDeclarationStatement

I don't know the syntax construction myself. How to load the csv path?

2条回答
SAY GOODBYE
2楼-- · 2019-03-01 20:24

To correct the Java syntax error, you need to escape double quotes in the middle of the string; otherwise it looks like your string literal finishes at the quote around the path:

"LOAD CSV WITH HEADERS FROM \"C:/..../Mock_data.csv\" AS csvLine "
查看更多
爷、活的狠高调
3楼-- · 2019-03-01 20:28

Finally this Worked for me!!

ExecutionResult result = engine.execute("LOAD CSV WITH HEADERS FROM 'file:///Users/xxxxx/Documents/Txx.csv' AS csvLine ")
查看更多
登录 后发表回答