How to properly return a StatementResult with a Transaction function?
Maybe the title itself is enough to express my confusion. In one hand I read a lot that using transaction functions is the recommended way to use the neo4j java driver.
See Neo4j Java Driver
On the other hand, I see examples of codes, such as in Neo4j Java Driver 1.7 API where there is no transaction (or maybe it's implicit), and I like the idea of having a StatementResult
and iterating on it.
So what should I do ?
Is there a way of having the iterator of an auto-commit transation in a transaction function ? Should I keep using the execute()
function, the session.writeTransaction()
function ?
It seems to me that there is a lot of way of running a simple request, but it can't figure why, or if theses methods can be a bit mixed up.
I'm not very happy with writeTransaction
if I can only get a String out of it.
There is also the GitHub examples for this driver, especially the ResultRetain with the 'Record' object which is closer of what I'm looking for but without any iterator. It allows data to be extracted with accessers. Another close example is the ResultConsume but still no iterator.
Based on these examples I wrote the following code, it works as expected, with generator and getters.
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
public class InitializeUser extends Logger{
StatementResult result;
public void getUserForInitialization(){
try ( Session session = driver.session() )
{
result = session.readTransaction( new TransactionWork<StatementResult>()
{
@Override
public StatementResult execute( Transaction tx )
{
return tx.run(
"MATCH (a{initialized:false}) "+
"RETURN a.username as username");
}
} );
}
}
public void readGenerator(){
while (result.hasNext())
{
Record record = result.next();
System.out.println(record.get("username").asString());
}
}
}
I'm not sure if it's worse or better than following the ResultRetain or the ResultConsume example but it has a generator, getters and what I think is transaction functions. I'm still very open to suggestions and explanations.
If someone could explain a bit the mechanic behind TransactionWork()
, execute()
, and what is the difference between readTransaction()
, writeTransaction()
, run()
and beginTransaction()
, I would be delighted.
Neo4j Java Driver
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
import static org.neo4j.driver.v1.Values.parameters;
public class HelloWorldExample implements AutoCloseable
{
private final Driver driver;
public HelloWorldExample( String uri, String user, String password )
{
driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ) );
}
@Override
public void close() throws Exception
{
driver.close();
}
public void printGreeting( final String message )
{
try ( Session session = driver.session() )
{
String greeting = session.writeTransaction( new TransactionWork<String>()
{
@Override
public String execute( Transaction tx )
{
StatementResult result = tx.run( "CREATE (a:Greeting) " +
"SET a.message = $message " +
"RETURN a.message + ', from node ' + id(a)",
parameters( "message", message ) );
return result.single().get( 0 ).asString();
}
} );
System.out.println( greeting );
}
}
public static void main( String... args ) throws Exception
{
try ( HelloWorldExample greeter = new HelloWorldExample( "bolt://localhost:7687", "neo4j", "password" ) )
{
greeter.printGreeting( "hello, world" );
}
}
}
Neo4j Java Driver 1.7 API
import org.neo4j.driver.v1.*;
import static org.neo4j.driver.v1.Values.parameters;
public class SmallExample
{
// Driver objects are thread-safe and are typically made available application-wide.
Driver driver;
public SmallExample(String uri, String user, String password)
{
driver = GraphDatabase.driver(uri, AuthTokens.basic(user, password));
}
private void addPerson(String name)
{
// Sessions are lightweight and disposable connection wrappers.
try (Session session = driver.session())
{
// Wrapping Cypher in an explicit transaction provides atomicity
// and makes handling errors much easier.
try (Transaction tx = session.beginTransaction())
{
tx.run("MERGE (a:Person {name: {x}})", parameters("x", name));
tx.success(); // Mark this write as successful.
}
}
}
private void printPeople(String initial)
{
try (Session session = driver.session())
{
// Auto-commit transactions are a quick and easy way to wrap a read.
StatementResult result = session.run(
"MATCH (a:Person) WHERE a.name STARTS WITH {x} RETURN a.name AS name",
parameters("x", initial));
// Each Cypher execution returns a stream of records.
while (result.hasNext())
{
Record record = result.next();
// Values can be extracted from a record by index or name.
System.out.println(record.get("name").asString());
}
}
}
public void close()
{
// Closing a driver immediately shuts down all open connections.
driver.close();
}
public static void main(String... args)
{
SmallExample example = new SmallExample("bolt://localhost:7687", "neo4j", "password");
example.addPerson("Ada");
example.addPerson("Alice");
example.addPerson("Bob");
example.printPeople("A");
example.close();
}
}
Neo4j Java Driver ResultRetainExample
import java.util.List;
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
import static org.neo4j.driver.v1.Values.parameters;
// end::result-retain-import
public class ResultRetainExample extends BaseApplication
{
public ResultRetainExample( String uri, String user, String password )
{
super( uri, user, password );
}
// tag::result-retain
public int addEmployees( final String companyName )
{
try ( Session session = driver.session() )
{
int employees = 0;
List<Record> persons = session.readTransaction( new TransactionWork<List<Record>>()
{
@Override
public List<Record> execute( Transaction tx )
{
return matchPersonNodes( tx );
}
} );
for ( final Record person : persons )
{
employees += session.writeTransaction( new TransactionWork<Integer>()
{
@Override
public Integer execute( Transaction tx )
{
tx.run( "MATCH (emp:Person {name: $person_name}) " +
"MERGE (com:Company {name: $company_name}) " +
"MERGE (emp)-[:WORKS_FOR]->(com)",
parameters( "person_name", person.get( "name" ).asString(), "company_name",
companyName ) );
return 1;
}
} );
}
return employees;
}
}
private static List<Record> matchPersonNodes( Transaction tx )
{
return tx.run( "MATCH (a:Person) RETURN a.name AS name" ).list();
}
// end::result-retain
}
Neo4j Java Driver ResultConsumeExample
import java.util.ArrayList;
import java.util.List;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
// end::result-consume-import
public class ResultConsumeExample extends BaseApplication
{
public ResultConsumeExample( String uri, String user, String password )
{
super( uri, user, password );
}
// tag::result-consume
public List<String> getPeople()
{
try ( Session session = driver.session() )
{
return session.readTransaction( new TransactionWork<List<String>>()
{
@Override
public List<String> execute( Transaction tx )
{
return matchPersonNodes( tx );
}
} );
}
}
private static List<String> matchPersonNodes( Transaction tx )
{
List<String> names = new ArrayList<>();
StatementResult result = tx.run( "MATCH (a:Person) RETURN a.name ORDER BY a.name" );
while ( result.hasNext() )
{
names.add( result.next().get( 0 ).asString() );
}
return names;
}
// end::result-consume
}
java neo4j driver
add a comment |
Maybe the title itself is enough to express my confusion. In one hand I read a lot that using transaction functions is the recommended way to use the neo4j java driver.
See Neo4j Java Driver
On the other hand, I see examples of codes, such as in Neo4j Java Driver 1.7 API where there is no transaction (or maybe it's implicit), and I like the idea of having a StatementResult
and iterating on it.
So what should I do ?
Is there a way of having the iterator of an auto-commit transation in a transaction function ? Should I keep using the execute()
function, the session.writeTransaction()
function ?
It seems to me that there is a lot of way of running a simple request, but it can't figure why, or if theses methods can be a bit mixed up.
I'm not very happy with writeTransaction
if I can only get a String out of it.
There is also the GitHub examples for this driver, especially the ResultRetain with the 'Record' object which is closer of what I'm looking for but without any iterator. It allows data to be extracted with accessers. Another close example is the ResultConsume but still no iterator.
Based on these examples I wrote the following code, it works as expected, with generator and getters.
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
public class InitializeUser extends Logger{
StatementResult result;
public void getUserForInitialization(){
try ( Session session = driver.session() )
{
result = session.readTransaction( new TransactionWork<StatementResult>()
{
@Override
public StatementResult execute( Transaction tx )
{
return tx.run(
"MATCH (a{initialized:false}) "+
"RETURN a.username as username");
}
} );
}
}
public void readGenerator(){
while (result.hasNext())
{
Record record = result.next();
System.out.println(record.get("username").asString());
}
}
}
I'm not sure if it's worse or better than following the ResultRetain or the ResultConsume example but it has a generator, getters and what I think is transaction functions. I'm still very open to suggestions and explanations.
If someone could explain a bit the mechanic behind TransactionWork()
, execute()
, and what is the difference between readTransaction()
, writeTransaction()
, run()
and beginTransaction()
, I would be delighted.
Neo4j Java Driver
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
import static org.neo4j.driver.v1.Values.parameters;
public class HelloWorldExample implements AutoCloseable
{
private final Driver driver;
public HelloWorldExample( String uri, String user, String password )
{
driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ) );
}
@Override
public void close() throws Exception
{
driver.close();
}
public void printGreeting( final String message )
{
try ( Session session = driver.session() )
{
String greeting = session.writeTransaction( new TransactionWork<String>()
{
@Override
public String execute( Transaction tx )
{
StatementResult result = tx.run( "CREATE (a:Greeting) " +
"SET a.message = $message " +
"RETURN a.message + ', from node ' + id(a)",
parameters( "message", message ) );
return result.single().get( 0 ).asString();
}
} );
System.out.println( greeting );
}
}
public static void main( String... args ) throws Exception
{
try ( HelloWorldExample greeter = new HelloWorldExample( "bolt://localhost:7687", "neo4j", "password" ) )
{
greeter.printGreeting( "hello, world" );
}
}
}
Neo4j Java Driver 1.7 API
import org.neo4j.driver.v1.*;
import static org.neo4j.driver.v1.Values.parameters;
public class SmallExample
{
// Driver objects are thread-safe and are typically made available application-wide.
Driver driver;
public SmallExample(String uri, String user, String password)
{
driver = GraphDatabase.driver(uri, AuthTokens.basic(user, password));
}
private void addPerson(String name)
{
// Sessions are lightweight and disposable connection wrappers.
try (Session session = driver.session())
{
// Wrapping Cypher in an explicit transaction provides atomicity
// and makes handling errors much easier.
try (Transaction tx = session.beginTransaction())
{
tx.run("MERGE (a:Person {name: {x}})", parameters("x", name));
tx.success(); // Mark this write as successful.
}
}
}
private void printPeople(String initial)
{
try (Session session = driver.session())
{
// Auto-commit transactions are a quick and easy way to wrap a read.
StatementResult result = session.run(
"MATCH (a:Person) WHERE a.name STARTS WITH {x} RETURN a.name AS name",
parameters("x", initial));
// Each Cypher execution returns a stream of records.
while (result.hasNext())
{
Record record = result.next();
// Values can be extracted from a record by index or name.
System.out.println(record.get("name").asString());
}
}
}
public void close()
{
// Closing a driver immediately shuts down all open connections.
driver.close();
}
public static void main(String... args)
{
SmallExample example = new SmallExample("bolt://localhost:7687", "neo4j", "password");
example.addPerson("Ada");
example.addPerson("Alice");
example.addPerson("Bob");
example.printPeople("A");
example.close();
}
}
Neo4j Java Driver ResultRetainExample
import java.util.List;
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
import static org.neo4j.driver.v1.Values.parameters;
// end::result-retain-import
public class ResultRetainExample extends BaseApplication
{
public ResultRetainExample( String uri, String user, String password )
{
super( uri, user, password );
}
// tag::result-retain
public int addEmployees( final String companyName )
{
try ( Session session = driver.session() )
{
int employees = 0;
List<Record> persons = session.readTransaction( new TransactionWork<List<Record>>()
{
@Override
public List<Record> execute( Transaction tx )
{
return matchPersonNodes( tx );
}
} );
for ( final Record person : persons )
{
employees += session.writeTransaction( new TransactionWork<Integer>()
{
@Override
public Integer execute( Transaction tx )
{
tx.run( "MATCH (emp:Person {name: $person_name}) " +
"MERGE (com:Company {name: $company_name}) " +
"MERGE (emp)-[:WORKS_FOR]->(com)",
parameters( "person_name", person.get( "name" ).asString(), "company_name",
companyName ) );
return 1;
}
} );
}
return employees;
}
}
private static List<Record> matchPersonNodes( Transaction tx )
{
return tx.run( "MATCH (a:Person) RETURN a.name AS name" ).list();
}
// end::result-retain
}
Neo4j Java Driver ResultConsumeExample
import java.util.ArrayList;
import java.util.List;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
// end::result-consume-import
public class ResultConsumeExample extends BaseApplication
{
public ResultConsumeExample( String uri, String user, String password )
{
super( uri, user, password );
}
// tag::result-consume
public List<String> getPeople()
{
try ( Session session = driver.session() )
{
return session.readTransaction( new TransactionWork<List<String>>()
{
@Override
public List<String> execute( Transaction tx )
{
return matchPersonNodes( tx );
}
} );
}
}
private static List<String> matchPersonNodes( Transaction tx )
{
List<String> names = new ArrayList<>();
StatementResult result = tx.run( "MATCH (a:Person) RETURN a.name ORDER BY a.name" );
while ( result.hasNext() )
{
names.add( result.next().get( 0 ).asString() );
}
return names;
}
// end::result-consume
}
java neo4j driver
I don't want to use OGM because I have read that the performances are not as good as what they are with pure Cypher. I don't know if it's still true but I'm not brave enough to write the tests. I have read that here : neo4j.com/blog/cypher-write-fast-furious
– machinus
Jan 3 at 11:05
Let us continue this discussion in chat.
– Guy Coder
Jan 3 at 11:33
add a comment |
Maybe the title itself is enough to express my confusion. In one hand I read a lot that using transaction functions is the recommended way to use the neo4j java driver.
See Neo4j Java Driver
On the other hand, I see examples of codes, such as in Neo4j Java Driver 1.7 API where there is no transaction (or maybe it's implicit), and I like the idea of having a StatementResult
and iterating on it.
So what should I do ?
Is there a way of having the iterator of an auto-commit transation in a transaction function ? Should I keep using the execute()
function, the session.writeTransaction()
function ?
It seems to me that there is a lot of way of running a simple request, but it can't figure why, or if theses methods can be a bit mixed up.
I'm not very happy with writeTransaction
if I can only get a String out of it.
There is also the GitHub examples for this driver, especially the ResultRetain with the 'Record' object which is closer of what I'm looking for but without any iterator. It allows data to be extracted with accessers. Another close example is the ResultConsume but still no iterator.
Based on these examples I wrote the following code, it works as expected, with generator and getters.
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
public class InitializeUser extends Logger{
StatementResult result;
public void getUserForInitialization(){
try ( Session session = driver.session() )
{
result = session.readTransaction( new TransactionWork<StatementResult>()
{
@Override
public StatementResult execute( Transaction tx )
{
return tx.run(
"MATCH (a{initialized:false}) "+
"RETURN a.username as username");
}
} );
}
}
public void readGenerator(){
while (result.hasNext())
{
Record record = result.next();
System.out.println(record.get("username").asString());
}
}
}
I'm not sure if it's worse or better than following the ResultRetain or the ResultConsume example but it has a generator, getters and what I think is transaction functions. I'm still very open to suggestions and explanations.
If someone could explain a bit the mechanic behind TransactionWork()
, execute()
, and what is the difference between readTransaction()
, writeTransaction()
, run()
and beginTransaction()
, I would be delighted.
Neo4j Java Driver
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
import static org.neo4j.driver.v1.Values.parameters;
public class HelloWorldExample implements AutoCloseable
{
private final Driver driver;
public HelloWorldExample( String uri, String user, String password )
{
driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ) );
}
@Override
public void close() throws Exception
{
driver.close();
}
public void printGreeting( final String message )
{
try ( Session session = driver.session() )
{
String greeting = session.writeTransaction( new TransactionWork<String>()
{
@Override
public String execute( Transaction tx )
{
StatementResult result = tx.run( "CREATE (a:Greeting) " +
"SET a.message = $message " +
"RETURN a.message + ', from node ' + id(a)",
parameters( "message", message ) );
return result.single().get( 0 ).asString();
}
} );
System.out.println( greeting );
}
}
public static void main( String... args ) throws Exception
{
try ( HelloWorldExample greeter = new HelloWorldExample( "bolt://localhost:7687", "neo4j", "password" ) )
{
greeter.printGreeting( "hello, world" );
}
}
}
Neo4j Java Driver 1.7 API
import org.neo4j.driver.v1.*;
import static org.neo4j.driver.v1.Values.parameters;
public class SmallExample
{
// Driver objects are thread-safe and are typically made available application-wide.
Driver driver;
public SmallExample(String uri, String user, String password)
{
driver = GraphDatabase.driver(uri, AuthTokens.basic(user, password));
}
private void addPerson(String name)
{
// Sessions are lightweight and disposable connection wrappers.
try (Session session = driver.session())
{
// Wrapping Cypher in an explicit transaction provides atomicity
// and makes handling errors much easier.
try (Transaction tx = session.beginTransaction())
{
tx.run("MERGE (a:Person {name: {x}})", parameters("x", name));
tx.success(); // Mark this write as successful.
}
}
}
private void printPeople(String initial)
{
try (Session session = driver.session())
{
// Auto-commit transactions are a quick and easy way to wrap a read.
StatementResult result = session.run(
"MATCH (a:Person) WHERE a.name STARTS WITH {x} RETURN a.name AS name",
parameters("x", initial));
// Each Cypher execution returns a stream of records.
while (result.hasNext())
{
Record record = result.next();
// Values can be extracted from a record by index or name.
System.out.println(record.get("name").asString());
}
}
}
public void close()
{
// Closing a driver immediately shuts down all open connections.
driver.close();
}
public static void main(String... args)
{
SmallExample example = new SmallExample("bolt://localhost:7687", "neo4j", "password");
example.addPerson("Ada");
example.addPerson("Alice");
example.addPerson("Bob");
example.printPeople("A");
example.close();
}
}
Neo4j Java Driver ResultRetainExample
import java.util.List;
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
import static org.neo4j.driver.v1.Values.parameters;
// end::result-retain-import
public class ResultRetainExample extends BaseApplication
{
public ResultRetainExample( String uri, String user, String password )
{
super( uri, user, password );
}
// tag::result-retain
public int addEmployees( final String companyName )
{
try ( Session session = driver.session() )
{
int employees = 0;
List<Record> persons = session.readTransaction( new TransactionWork<List<Record>>()
{
@Override
public List<Record> execute( Transaction tx )
{
return matchPersonNodes( tx );
}
} );
for ( final Record person : persons )
{
employees += session.writeTransaction( new TransactionWork<Integer>()
{
@Override
public Integer execute( Transaction tx )
{
tx.run( "MATCH (emp:Person {name: $person_name}) " +
"MERGE (com:Company {name: $company_name}) " +
"MERGE (emp)-[:WORKS_FOR]->(com)",
parameters( "person_name", person.get( "name" ).asString(), "company_name",
companyName ) );
return 1;
}
} );
}
return employees;
}
}
private static List<Record> matchPersonNodes( Transaction tx )
{
return tx.run( "MATCH (a:Person) RETURN a.name AS name" ).list();
}
// end::result-retain
}
Neo4j Java Driver ResultConsumeExample
import java.util.ArrayList;
import java.util.List;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
// end::result-consume-import
public class ResultConsumeExample extends BaseApplication
{
public ResultConsumeExample( String uri, String user, String password )
{
super( uri, user, password );
}
// tag::result-consume
public List<String> getPeople()
{
try ( Session session = driver.session() )
{
return session.readTransaction( new TransactionWork<List<String>>()
{
@Override
public List<String> execute( Transaction tx )
{
return matchPersonNodes( tx );
}
} );
}
}
private static List<String> matchPersonNodes( Transaction tx )
{
List<String> names = new ArrayList<>();
StatementResult result = tx.run( "MATCH (a:Person) RETURN a.name ORDER BY a.name" );
while ( result.hasNext() )
{
names.add( result.next().get( 0 ).asString() );
}
return names;
}
// end::result-consume
}
java neo4j driver
Maybe the title itself is enough to express my confusion. In one hand I read a lot that using transaction functions is the recommended way to use the neo4j java driver.
See Neo4j Java Driver
On the other hand, I see examples of codes, such as in Neo4j Java Driver 1.7 API where there is no transaction (or maybe it's implicit), and I like the idea of having a StatementResult
and iterating on it.
So what should I do ?
Is there a way of having the iterator of an auto-commit transation in a transaction function ? Should I keep using the execute()
function, the session.writeTransaction()
function ?
It seems to me that there is a lot of way of running a simple request, but it can't figure why, or if theses methods can be a bit mixed up.
I'm not very happy with writeTransaction
if I can only get a String out of it.
There is also the GitHub examples for this driver, especially the ResultRetain with the 'Record' object which is closer of what I'm looking for but without any iterator. It allows data to be extracted with accessers. Another close example is the ResultConsume but still no iterator.
Based on these examples I wrote the following code, it works as expected, with generator and getters.
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
public class InitializeUser extends Logger{
StatementResult result;
public void getUserForInitialization(){
try ( Session session = driver.session() )
{
result = session.readTransaction( new TransactionWork<StatementResult>()
{
@Override
public StatementResult execute( Transaction tx )
{
return tx.run(
"MATCH (a{initialized:false}) "+
"RETURN a.username as username");
}
} );
}
}
public void readGenerator(){
while (result.hasNext())
{
Record record = result.next();
System.out.println(record.get("username").asString());
}
}
}
I'm not sure if it's worse or better than following the ResultRetain or the ResultConsume example but it has a generator, getters and what I think is transaction functions. I'm still very open to suggestions and explanations.
If someone could explain a bit the mechanic behind TransactionWork()
, execute()
, and what is the difference between readTransaction()
, writeTransaction()
, run()
and beginTransaction()
, I would be delighted.
Neo4j Java Driver
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
import static org.neo4j.driver.v1.Values.parameters;
public class HelloWorldExample implements AutoCloseable
{
private final Driver driver;
public HelloWorldExample( String uri, String user, String password )
{
driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ) );
}
@Override
public void close() throws Exception
{
driver.close();
}
public void printGreeting( final String message )
{
try ( Session session = driver.session() )
{
String greeting = session.writeTransaction( new TransactionWork<String>()
{
@Override
public String execute( Transaction tx )
{
StatementResult result = tx.run( "CREATE (a:Greeting) " +
"SET a.message = $message " +
"RETURN a.message + ', from node ' + id(a)",
parameters( "message", message ) );
return result.single().get( 0 ).asString();
}
} );
System.out.println( greeting );
}
}
public static void main( String... args ) throws Exception
{
try ( HelloWorldExample greeter = new HelloWorldExample( "bolt://localhost:7687", "neo4j", "password" ) )
{
greeter.printGreeting( "hello, world" );
}
}
}
Neo4j Java Driver 1.7 API
import org.neo4j.driver.v1.*;
import static org.neo4j.driver.v1.Values.parameters;
public class SmallExample
{
// Driver objects are thread-safe and are typically made available application-wide.
Driver driver;
public SmallExample(String uri, String user, String password)
{
driver = GraphDatabase.driver(uri, AuthTokens.basic(user, password));
}
private void addPerson(String name)
{
// Sessions are lightweight and disposable connection wrappers.
try (Session session = driver.session())
{
// Wrapping Cypher in an explicit transaction provides atomicity
// and makes handling errors much easier.
try (Transaction tx = session.beginTransaction())
{
tx.run("MERGE (a:Person {name: {x}})", parameters("x", name));
tx.success(); // Mark this write as successful.
}
}
}
private void printPeople(String initial)
{
try (Session session = driver.session())
{
// Auto-commit transactions are a quick and easy way to wrap a read.
StatementResult result = session.run(
"MATCH (a:Person) WHERE a.name STARTS WITH {x} RETURN a.name AS name",
parameters("x", initial));
// Each Cypher execution returns a stream of records.
while (result.hasNext())
{
Record record = result.next();
// Values can be extracted from a record by index or name.
System.out.println(record.get("name").asString());
}
}
}
public void close()
{
// Closing a driver immediately shuts down all open connections.
driver.close();
}
public static void main(String... args)
{
SmallExample example = new SmallExample("bolt://localhost:7687", "neo4j", "password");
example.addPerson("Ada");
example.addPerson("Alice");
example.addPerson("Bob");
example.printPeople("A");
example.close();
}
}
Neo4j Java Driver ResultRetainExample
import java.util.List;
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
import static org.neo4j.driver.v1.Values.parameters;
// end::result-retain-import
public class ResultRetainExample extends BaseApplication
{
public ResultRetainExample( String uri, String user, String password )
{
super( uri, user, password );
}
// tag::result-retain
public int addEmployees( final String companyName )
{
try ( Session session = driver.session() )
{
int employees = 0;
List<Record> persons = session.readTransaction( new TransactionWork<List<Record>>()
{
@Override
public List<Record> execute( Transaction tx )
{
return matchPersonNodes( tx );
}
} );
for ( final Record person : persons )
{
employees += session.writeTransaction( new TransactionWork<Integer>()
{
@Override
public Integer execute( Transaction tx )
{
tx.run( "MATCH (emp:Person {name: $person_name}) " +
"MERGE (com:Company {name: $company_name}) " +
"MERGE (emp)-[:WORKS_FOR]->(com)",
parameters( "person_name", person.get( "name" ).asString(), "company_name",
companyName ) );
return 1;
}
} );
}
return employees;
}
}
private static List<Record> matchPersonNodes( Transaction tx )
{
return tx.run( "MATCH (a:Person) RETURN a.name AS name" ).list();
}
// end::result-retain
}
Neo4j Java Driver ResultConsumeExample
import java.util.ArrayList;
import java.util.List;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.TransactionWork;
// end::result-consume-import
public class ResultConsumeExample extends BaseApplication
{
public ResultConsumeExample( String uri, String user, String password )
{
super( uri, user, password );
}
// tag::result-consume
public List<String> getPeople()
{
try ( Session session = driver.session() )
{
return session.readTransaction( new TransactionWork<List<String>>()
{
@Override
public List<String> execute( Transaction tx )
{
return matchPersonNodes( tx );
}
} );
}
}
private static List<String> matchPersonNodes( Transaction tx )
{
List<String> names = new ArrayList<>();
StatementResult result = tx.run( "MATCH (a:Person) RETURN a.name ORDER BY a.name" );
while ( result.hasNext() )
{
names.add( result.next().get( 0 ).asString() );
}
return names;
}
// end::result-consume
}
java neo4j driver
java neo4j driver
edited Jan 4 at 8:28
machinus
asked Jan 3 at 10:15
machinusmachinus
2915
2915
I don't want to use OGM because I have read that the performances are not as good as what they are with pure Cypher. I don't know if it's still true but I'm not brave enough to write the tests. I have read that here : neo4j.com/blog/cypher-write-fast-furious
– machinus
Jan 3 at 11:05
Let us continue this discussion in chat.
– Guy Coder
Jan 3 at 11:33
add a comment |
I don't want to use OGM because I have read that the performances are not as good as what they are with pure Cypher. I don't know if it's still true but I'm not brave enough to write the tests. I have read that here : neo4j.com/blog/cypher-write-fast-furious
– machinus
Jan 3 at 11:05
Let us continue this discussion in chat.
– Guy Coder
Jan 3 at 11:33
I don't want to use OGM because I have read that the performances are not as good as what they are with pure Cypher. I don't know if it's still true but I'm not brave enough to write the tests. I have read that here : neo4j.com/blog/cypher-write-fast-furious
– machinus
Jan 3 at 11:05
I don't want to use OGM because I have read that the performances are not as good as what they are with pure Cypher. I don't know if it's still true but I'm not brave enough to write the tests. I have read that here : neo4j.com/blog/cypher-write-fast-furious
– machinus
Jan 3 at 11:05
Let us continue this discussion in chat.
– Guy Coder
Jan 3 at 11:33
Let us continue this discussion in chat.
– Guy Coder
Jan 3 at 11:33
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54020235%2fhow-to-properly-return-a-statementresult-with-a-transaction-function%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54020235%2fhow-to-properly-return-a-statementresult-with-a-transaction-function%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I don't want to use OGM because I have read that the performances are not as good as what they are with pure Cypher. I don't know if it's still true but I'm not brave enough to write the tests. I have read that here : neo4j.com/blog/cypher-write-fast-furious
– machinus
Jan 3 at 11:05
Let us continue this discussion in chat.
– Guy Coder
Jan 3 at 11:33