Query Neo4j with Cypher using the REST API

complete-graph

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:

<dependencies>
   ...
   <dependency>
      <groupId>org.murygin</groupId>
      <artifactId>jgrapht-neo4j-client</artifactId>
      <version>0.1</version>
   </dependency>
   ...
</dependencies>
...
<repositories>
   ...
   <repository>
      <id>git-murygin</id>
       <name>Murygin's Git based repo</name>
       <url>https://github.com/murygin/maven-repository/raw/master/</url>
   </repository>
   ...
</repositories> 

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();
cypher.setHost("HOSTNAME");
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) {
  setQuery(query);
  execute();
  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();
  setJsonString(response.getEntity(String.class)); 
  response.close();
  if (LOG.isDebugEnabled()) {
    LOG.debug(getJsonString());
  } 
  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
    .accept(MediaType.APPLICATION_JSON)
    .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

Schreibe einen Kommentar

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

WordPress.com-Logo

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

Twitter-Bild

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

Facebook-Foto

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

Google+ Foto

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

Verbinde mit %s

%d Bloggern gefällt das: