Query Neo4j with Cypher using the REST API


Neo4j REST API provides a way to query the database with Cypher. Cypher is a declarative graph query language. See the Neo4j manual to learn more about it. In this article I will show how to use the REST API to execute Cypher queries from Java code.

My class CypherToJson is using Jersey to make REST calls and simple-json to encode and decode JSON text. The code is on GitHub in repository jgrapht-neo4j-client. Here you can find a Jar with the class: jgrapht-neo4j-client-0.1.jar. To use the class in Maven projects you have to add a new dependency and repository to your pom.xml:

       <name>Murygin's Git based repo</name>

First I will show how to use the class after that you will find some implementation details.

The following code snippet shows how to execute a query:

CypherToJson cypher = new CypherToJson();
JSONObject json = cypher.execute("MATCH n-[r]-() RETURN n,r");
String jsonString = cypher.getJsonString(); // or
JSONObject json = cypher.getJson();
JSONArray results = (JSONArray) json.get("results");

This code executes the query MATCH n-[r]-() RETURN n,r and returns the result as an JSON string or a JSON object. You can learn more about the JSON result object in the Neo4j documentation in chapter: Return results in graph format.

Lets have a look in class CypherToJson. Method execute(String query) is just a wrapper which set the query, executes it and returns the result.

public JSONObject execute(String query) {
  return getJson();

Method execute() sent the request to the web service with a Jersey client and creates the simple-json object out of the response:

public void execute() {
  ClientResponse response = excecuteRequest();
  if (LOG.isDebugEnabled()) {
  JSONParser parser = new JSONParser();
  try {
    setJson((JSONObject) parser.parse(getJsonString()));
  } catch (ParseException e) {
    throw new RuntimeException(
      "Error while parsing json: " + getJsonString(), e);

private ClientResponse excecuteRequest() {
  Client client = Client.create();
  WebResource webResource = client.resource(createUri());
  String request = createJsonString();
  ClientResponse response = webResource
    .type( MediaType.APPLICATION_JSON )
    .post(ClientResponse.class, request);
  if (response.getStatus() != 200) {
    throw new RuntimeException(
      "Failed : HTTP error code : " + response.getStatus());
  return response;
  1. 25. Juni 2015

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:


Du kommentierst mit Deinem WordPress.com-Konto. Abmelden /  Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden /  Ändern )


Du kommentierst mit Deinem Twitter-Konto. Abmelden /  Ändern )


Du kommentierst mit Deinem Facebook-Konto. Abmelden /  Ändern )


Verbinde mit %s

%d Bloggern gefällt das: