Cypher queries
In Java, you can use the Cypher query language as per the example below.
The source code for the examples can befound at: JavaQuery.java |
First, you can add some data:
DatabaseManagementService managementService = new DatabaseManagementServiceBuilder( databaseDirectory ).build();
GraphDatabaseService db = managementService.database( DEFAULT_DATABASE_NAME );
try ( Transaction tx = db.beginTx())
{
Node myNode = tx.createNode();
myNode.setProperty( "name", "my node" );
tx.commit();
}
Execute a query:
try ( Transaction tx = db.beginTx();
Result result = tx.execute( "MATCH (n {name: 'my node'}) RETURN n, n.name" ) )
{
while ( result.hasNext() )
{
Map<String,Object> row = result.next();
for ( Entry<String,Object> column : row.entrySet() )
{
rows += column.getKey() + ": " + column.getValue() + "; ";
}
rows += "\n";
}
}
In this example, you can also see how to iterate over the rows of the org.neo4j.graphdb.Result
.
The code will generate:
n: Node[0]; n.name: my node;
When using the |
The recommended way to handle results is to use a try-with-resources statement. This ensures that the result is closed at the end of the statement.
You can also get a list of the columns in the result:
List<String> columns = result.columns();
This gives you:
[n, n.name]
Use the following to fetch the result items from a single column. In this case, you must read the property from the node, and not from the result:
Iterator<Node> n_column = result.columnAs( "n" );
n_column.forEachRemaining( node -> nodeResult = node + ": " + node.getProperty( "name" ) );
In this case, there is only one node in the result:
Node[0]: my node
Use this only if the result contains a single column or you are interested in a single column of the result.
|
For more information on the Java interface to Cypher, see the Neo4j Javadocs.
For more information and examples for Cypher, see Neo4j Cypher Manual.