Reader small image

You're reading from  Learning Neo4j 3.x - Second Edition

Product typeBook
Published inOct 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781786466143
Edition2nd Edition
Languages
Tools
Concepts
Right arrow
Author (1)
Jerome Baton
Jerome Baton
author image
Jerome Baton

Jérôme Baton started hacking computers at the age of skin problems, gaming first then continued his trip by self-learning Basic on Amstrad CPC, peaking on coding a full screen horizontal starfield, and messing the interlace of the video controller so that sprites appeared twice as high in horizontal beat'em up games. Disks were three inches for 178 Kb then. Then, for gaming reasons, he switched to Commodore Amiga and its fantastic AMOS Basic. Later caught by seriousness and studies, he wrote Turbo Pascal, C, COBOL, Visual C++, and Java on PCs and mainframes at university, and even Logo in high school. Then, Java happened and he became a consultant, mostly on backend code of websites in many different businesses. Jérôme authored several articles in French on Neo4j, JBoss Forge, an Arduino workshop for Devoxx4Kids, and reviewed kilos of books on Android. He has a weakness for wordplay, puns, spoonerisms, and Neo4j that relieves him from join(t) pains. Jérôme also has the joy to teach in French universities, currently at I.U.T de Paris, Université Paris V - René Descartes (Neo4j, Android), and Université de Troyes (Neo4j), where he does his best to enterTRain the students. When not programming, Jérôme enjoys photography, doing electronics, everything DIY, understanding how things work, trying to be clever or funny on Twitter, and spends a lot of time trying to understand his kids and life in general.
Read more about Jerome Baton

Right arrow

Chapter 6. Extending Cypher

Now that we have seen Cypher and the famous APOC project, we will talk about adding functions and procedures to a Neo4j instance, just like writing your own APOC for your projects, except that your extensions are more directly related to your business.  

In this chapter, we will cover the following topics:

  • Building an extension project (plugin)
  • User-defined functions 
  • User-defined procedures
  • Custom aggregators
  • Unmanaged extensions
  • Streaming JSON responses

Let's empower ourselves with more knowledge.

Building an extension project


The kind people at Neo4j are always keen to ease the workload of their users, so they have created a Maven-based template project on GitHub for us to get a quickstart on our functions and procedures. This way, no time is wasted looking for the dependencies.

Cheers guys!

The project is hosted at https://github.com/neo4j-examples/neo4j-procedure-template. You can either download or clone it, and then open your copy in your favorite Java IDE. In the pom.xml file, update the neo4j.version property with the value corresponding to the version of the Neo4j server that you use. In my case, it is the following:

<properties>
  <neo4j.version>3.2.0</neo4j.version>
</properties>

Build the project with your IDE. There should be no error at this stage. We will use the same project for all kinds of code we will write.

Creating a function

This is not rocket science, a function is just a method in a Java class. This method must be annotated with @UserFunction...

Custom aggregators


Some of the most common aggregators in the SQL world are count, sum, min, or max. They are used in conjunction with the GROUP BY instruction. Here is an example of aggregator usage in Cypher:

MATCH (p:Person)-[IS_NAMED]-(ln:LastName)
RETURN ln.lastName, count(p)

Since version 3.2, Neo4j allows you to create your own aggregators, which is fairly simple. To illustrate, we will see how to code a random count: a count aggregator that returns a random value. The Java code is as follows:

package learningneo4j;

import org.neo4j.procedure.*;

public class RandomCount {
@UserAggregationFunction("learningneo4j.randomCount")
    @Description( "learningneo4j.randomCount - mostly returns a wrong value " )
    public RandomAggregator randomAggregator() {
        return new RandomAggregator();
    }

    public static class RandomAggregator {
        private long count;

@UserAggregationUpdate
        public void repeated(@Name("string") Object obj ){ // parameter 
          given as example...

Unmanaged extensions


Unmanaged extensions (UE) are a way to serve content from the Neo4j server but outside of its usual API endpoints. Strictly put, this is YOUR code, running on the server, in order to serve your data. More precisely, this is JAX-RS 2.0 code.

Note

JAX-RS is a Java API originating in Java EE 6, whose goal is to help develop web services according to the Representational State Transfer (REST) paradigm. The corresponding JSR is #339, and its expert group is constituted of Java gurus such as Adam Bien or Bill Burke.

In order to create a Maven-based project, after the initial creation with your favorite IDE, add those two dependencies to the pom.xml file:

<dependency>
  <groupId>org.neo4j</groupId>
  <artifactId>neo4j</artifactId>
  <version>${neo4j.version}</version><!-- This is a Maven property  -->
  <scope>provided</scope>
</dependency>

<dependency>
  <groupId>javax.ws.rs</groupId>
  <artifactId...

Summary


We came in to this chapter to learn how to add strings to our bow so that we can now create our own functions and procedures, specific to our projects (and models).

We saw that functions are for small tasks, and procedures are for tasks updating the graph. We saw what custom aggregators are made of. We saw that unmanaged extensions are custom REST entry points to the Neo4j server. We saw new possibilities to put into action in our projects.

We came, we saw, we conquered, or as Caesar would say: Veni, Vidi, Vici 

(you:Reader)-[:LEARNED]->(s:Sentence {language: "latin", meaning: "I came, I saw, I overcame"}

In the next chapter, we will see if we need to improve the performance of our queries, and if so, how to do it. Get ready !

 

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning Neo4j 3.x - Second Edition
Published in: Oct 2017Publisher: PacktISBN-13: 9781786466143
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Jerome Baton

Jérôme Baton started hacking computers at the age of skin problems, gaming first then continued his trip by self-learning Basic on Amstrad CPC, peaking on coding a full screen horizontal starfield, and messing the interlace of the video controller so that sprites appeared twice as high in horizontal beat'em up games. Disks were three inches for 178 Kb then. Then, for gaming reasons, he switched to Commodore Amiga and its fantastic AMOS Basic. Later caught by seriousness and studies, he wrote Turbo Pascal, C, COBOL, Visual C++, and Java on PCs and mainframes at university, and even Logo in high school. Then, Java happened and he became a consultant, mostly on backend code of websites in many different businesses. Jérôme authored several articles in French on Neo4j, JBoss Forge, an Arduino workshop for Devoxx4Kids, and reviewed kilos of books on Android. He has a weakness for wordplay, puns, spoonerisms, and Neo4j that relieves him from join(t) pains. Jérôme also has the joy to teach in French universities, currently at I.U.T de Paris, Université Paris V - René Descartes (Neo4j, Android), and Université de Troyes (Neo4j), where he does his best to enterTRain the students. When not programming, Jérôme enjoys photography, doing electronics, everything DIY, understanding how things work, trying to be clever or funny on Twitter, and spends a lot of time trying to understand his kids and life in general.
Read more about Jerome Baton