Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Your Next Neo4j App is Just a Few Lines of Code Away

DZone's Guide to

Your Next Neo4j App is Just a Few Lines of Code Away

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

The transactional http endpoint that was added to Neo4j 2.0 is really easy to use.

You can stream batches of cypher statements with their parameters to the server and receive the answers in a streaming fashion too.

The basic usage, of one transaction per batched request can be used with 3 lines of javascript.

var r=require("request")
function cypher(query,params,cb) {
  r.post({uri:"http://localhost:7474/db/data/transaction/commit",
          json:{statements:[{statement:query,parameters:params}]}},
        function(err,res) { cb(err,res.body)})
}

var query="MATCH (n:User) RETURN n, labels(n) as l LIMIT {limit}"
var params={limit: 10}
var cb=function(err,data) { console.log(JSON.stringify(data)) }

cypher(query,params,cb)

{"results":[
  {"columns":["n","l"],
   "data":[
    {"row":[{"name":"Aran"},["User"]]}
    ]
  }],
 "errors":[]}

It also supports transactions over the write. Meaning, you can across multiple http requests continue to read and write in your own isolated view of the world and then finally decide to keep your work (commit) or to throw it all away (rollback).

When you first post to /db/data/transaction the answer will contain the transaction-URL in the Location-Header. It also then provides a commit URL field in the JSON response and a transaction timeout date and time (by default 30s).

Here is a sample session:

Write-Request:
POST /db/data/transaction
{"statements":[
 {"statement": "CREATE (u:Person {login:{name}}) RETURN u",
  "parameters":{"name":"Peter"}}]}

Result: ==> 201 Created

{"commit": "http://localhost:7474/db/data/transaction/4/commit",
"results":
 [{
 "columns":["u"],
 "data":[{"row":[{"login":"Peter"}]}]}],
 "transaction":{"expires":"Wed, 18 Sep 2013 14:36:26 +0000"},
 "errors":[]}

Read-Request: POST /db/data/transaction/4
 {"statements": [{"statement":"MATCH (u:User) RETURN u"}]}
Result: ==> 200 OK
{"commit":
 "http://localhost:7474/db/data/transaction/4/commit",
 "results":
 [{"columns":["u"],
   "data":[{"row":[{"login":"Peter"}]}]}],
   "transaction":{"expires":"Wed, 18 Sep 2013 14:39:05.."},
   "errors":[]}

Commit-Request: POST /db/data/transaction/4/commit
Result: ==> 200 OK
{"results":[],"errors":[]}

Adding transactional support to the javascript snippet shown initially should be easy and is left as exercise for you :)


Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java ,nosql ,javascript ,tips and tricks ,neo4j

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}