Introduction to Spring Data Neo4j - Whiteship's...

120
Introduction to Spring Data Neo4j Michael Hunger 1 Donnerstag, 27. Oktober 2011

Transcript of Introduction to Spring Data Neo4j - Whiteship's...

Page 1: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Introduction to Spring Data Neo4j

Michael Hunger

1Donnerstag, 27. Oktober 2011

Page 2: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Me & You ?

๏Me: Michael Hunger, Neo Technology

• passionate software developer / Neo4j German Division

• Spring Data Neo4j Project Lead

•Neo4j Cloud Hosting

[email protected] / @mesirii

๏You:

•NOSQL ?

• Enterprise ?

•Rich Domain ?

( I just assume Java + Spring)

2Donnerstag, 27. Oktober 2011

Page 3: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What‘s up?

๏NOSQL overview

๏Spring Data overview

๏Networks are everywhere

๏Graph Databases

๏Neo4j introduction

๏Spring Data Neo4j introduction

3

3Donnerstag, 27. Oktober 2011

Page 4: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

NOSQL overview

4

4Donnerstag, 27. Oktober 2011

Page 5: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What does NOSQL stand for?

5Donnerstag, 27. Oktober 2011

Page 6: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What does NOSQL stand for?

It’s not “No to SQL”

5Donnerstag, 27. Oktober 2011

Page 7: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What does NOSQL stand for?

It’s not “No to SQL”

It’s not “Never SQL”

5Donnerstag, 27. Oktober 2011

Page 8: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What does NOSQL stand for?

It’s not “No to SQL”

It’s not “Never SQL”

It’s “Not Only SQL”

5Donnerstag, 27. Oktober 2011

Page 9: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What does NOSQL stand for?

It’s not “No to SQL”

It’s not “Never SQL”

It’s “Not Only SQL”

NOSQL \no-seek-wool\ n. Describes ongoing trend where developers increasingly opt for non-relational databases to help solve their problems, in an effort to use the right tool for the right job.

5Donnerstag, 27. Oktober 2011

Page 10: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Why NOSQL now?

๏Trend 1: Size of data is growing

๏Trend 2: Data is increasingly connected

๏Trend 3: Data is increasingly semi-structured

๏Trend 4: Change in architecture

We have observed four trends:

6Donnerstag, 27. Oktober 2011

Page 11: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

NOSQL categories

We see four main categories in the NOSQL space:•KVDynamo

•Column-familyBigTableDynamo-inspired

•DocumentLotus Notes

•GraphEuler & graph theoryConnections in brain

7Donnerstag, 27. Oktober 2011

Page 12: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

NOSQL categories

We see four main categories in the NOSQL space:

•Redis

•Riak

•Voldemort

Key-Value

•KVDynamo

•Column-familyBigTableDynamo-inspired

•DocumentLotus Notes

•GraphEuler & graph theoryConnections in brain

7Donnerstag, 27. Oktober 2011

Page 13: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

NOSQL categories

We see four main categories in the NOSQL space:

•Cassandra

•HBase

Column-family/BigTable

•Redis

•Riak

•Voldemort

Key-Value

•KVDynamo

•Column-familyBigTableDynamo-inspired

•DocumentLotus Notes

•GraphEuler & graph theoryConnections in brain

7Donnerstag, 27. Oktober 2011

Page 14: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

NOSQL categories

We see four main categories in the NOSQL space:

•Cassandra

•HBase

Column-family/BigTable

•Redis

•Riak

•Voldemort

Key-Value

•MongoDB

•CouchDB

Document

•KVDynamo

•Column-familyBigTableDynamo-inspired

•DocumentLotus Notes

•GraphEuler & graph theoryConnections in brain

7Donnerstag, 27. Oktober 2011

Page 15: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

NOSQL categories

We see four main categories in the NOSQL space:

•Cassandra

•HBase

Column-family/BigTable

•Redis

•Riak

•Voldemort

Key-Value

•MongoDB

•CouchDB

Document

•Neo4j

•InfiniteGraph

•OrientDB

•DEX

Graph

•KVDynamo

•Column-familyBigTableDynamo-inspired

•DocumentLotus Notes

•GraphEuler & graph theoryConnections in brain

7Donnerstag, 27. Oktober 2011

Page 16: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Scaling to size vs. Scaling to complexity

8

Size

Complexity

Key-Value stores

Bigtable clones

Document databases

Graph databases

8Donnerstag, 27. Oktober 2011

Page 17: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Scaling to size vs. Scaling to complexity

8

Size

Complexity

Key-Value stores

Bigtable clones

Document databases

Graph databases

Billions of nodesand relationships

8Donnerstag, 27. Oktober 2011

Page 18: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Scaling to size vs. Scaling to complexity

8

Size

Complexity

Key-Value stores

Bigtable clones

Document databases

Graph databases

> 90% of use cases

Billions of nodesand relationships

8Donnerstag, 27. Oktober 2011

Page 19: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Spring Data overview

9Donnerstag, 27. Oktober 2011

Page 20: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What is Spring Data

10

๏VMWare/SpringSource initiative to give Spring developers easy access to the emerging world of NOSQL, including:

•Non-relational databases

•MapReduce

•Grails NOSQL support

•Cross-store persistence

•Object Persistence Mapping Infrastructure

•Generic Repository Infrastructure

• upcoming Spring Roo add-ons

10Donnerstag, 27. Oktober 2011

Page 21: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Spring Data projects

๏Code is in SpringSource git repository:

• http://springsource.org/spring-data

• https://github.com/SpringSource/spring-data-*

๏ Includes:

• data-commons

• spring-data-graph-neo4j

• spring-data-{redis,riak}

• spring-data-mongo

• spring-data-jdbc

• spring-data-jpa

11Donnerstag, 27. Oktober 2011

Page 22: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Spring Data Neo4j

๏Focus on Spring Data Neo4j

๏VMWare is collaborating with Neo Technology, the company behind the Neo4j graph database.

๏Improved programming model: Annotation-based programming model for graph applications

๏Cross-store persistence: Extend existing JPA application with NOSQL persistence

๏Spring Roo support: Add graph persistence with Roo add-on

12Donnerstag, 27. Oktober 2011

Page 23: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

13

Graphs are everywhere

13Donnerstag, 27. Oktober 2011

Page 24: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Even in the Matrix- everything is a grpah

14

Google Image Search: „graph OR network“

14Donnerstag, 27. Oktober 2011

Page 25: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Graphs Everywhere

๏Relationships in

• Politics, Economics, History, Science, Transportation

๏Biology, Chemistry, Physics, Sociology

•Body, Ecosphere, Reaction, Interactions

๏ Internet

•Hardware, Software, Interaction

๏Social Networks

• Family, Friends

•Work, Communities

•Neighbours, Cities, Society 15

15Donnerstag, 27. Oktober 2011

Page 26: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Good Relationships

๏the world is rich, messy and related data

๏relationships are as least as important as the things they connect

๏Graphs = Whole > Sum of all parts

๏complex interactions

๏always changing, change of structures as well

๏Graph: Relationships are part of the data

๏RDBMS: Relationships part of the fixed schema

16

16Donnerstag, 27. Oktober 2011

Page 27: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Questions and Answers

๏Complex Questions

๏Answers lie between the lines (things)

๏Locality of the information

๏Global searches / operations very expensive

๏constant query time, regardless of data volume

17

17Donnerstag, 27. Oktober 2011

Page 28: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Categories ?

๏Categories == Classes, Trees ?

๏What if more than one category fits?

๏Tags

๏Categories vi relationships like „IS_A“

๏any number, easy change

๏„virtual“ Relationships - Traversals

๏Category dynamically derived from queries

18

18Donnerstag, 27. Oktober 2011

Page 29: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Fowler & Christakis „Connected“

19

19Donnerstag, 27. Oktober 2011

Page 30: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

New York Times R&D „Cascade“

20

20Donnerstag, 27. Oktober 2011

Page 31: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Deb Roy - MIT & Bluefin Labs

21

„Birth of a Word“ TED Talk

Researches Social Reactions to (Media) Events

21Donnerstag, 27. Oktober 2011

Page 32: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Neo4j introduction

22Donnerstag, 27. Oktober 2011

Page 33: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What is Neo4j?data model

23Donnerstag, 27. Oktober 2011

Page 34: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What is Neo4j?

A Graph Databasedata model

23Donnerstag, 27. Oktober 2011

Page 35: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What is Neo4j?

A Graph Databasedata model

23Donnerstag, 27. Oktober 2011

Page 36: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What is Neo4j?

A Graph Databasedata model

23Donnerstag, 27. Oktober 2011

Page 37: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What is Neo4j?

Node Node

A Graph Databasedata model

23Donnerstag, 27. Oktober 2011

Page 38: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What is Neo4j?

Node Node

A Graph Database

Typed relationship

data model

23Donnerstag, 27. Oktober 2011

Page 39: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What is Neo4j?

NodeNode

A Graph Database

Typed relationship

data model

key: value key: value

23Donnerstag, 27. Oktober 2011

Page 40: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

For example

24Donnerstag, 27. Oktober 2011

Page 41: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

For example

name: Oliver

24Donnerstag, 27. Oktober 2011

Page 42: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

For example

name: Oliver name: Michael

24Donnerstag, 27. Oktober 2011

Page 43: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

For example

name: Oliver name: MichaelWORKS_WITHproject: spring-data

24Donnerstag, 27. Oktober 2011

Page 44: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

For example

name: Oliver name: MichaelWORKS_WITHproject: spring-data

company: VMware

EMPLOYED_BY

city: Dresdencountry: DE

LIVE

S_IN

24Donnerstag, 27. Oktober 2011

Page 45: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

For example

name: Oliver name: MichaelWORKS_WITHproject: spring-data

company: VMware

EMPLOYED_BY

city: Dresdencountry: DE

LIVE

S_IN

name: Rod

KNOWS KNOWS

24Donnerstag, 27. Oktober 2011

Page 46: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

For example

name: Oliver name: MichaelWORKS_WITHproject: spring-data

company: VMware

EMPLOYED_BY

city: Dresdencountry: DE

LIVE

S_IN

name: Rod

KNOWS KNOWS

food: Chinese

LIKE

S

24Donnerstag, 27. Oktober 2011

Page 47: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Best NOSQL Database for Spring ?Why ? Explain !

•Written in Java •Embeddable or standalone Server•Schema-free - perfect for rich domains•Fully transactional (ACID)•Persistent to custom on-disk file structure•Traversal speeds of 1,000+ hops per ms•24/7 production since 2003•Integrated indexing•Plenthora of language bindings

25Donnerstag, 27. Oktober 2011

Page 48: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Whiteboard friendly

26Donnerstag, 27. Oktober 2011

Page 49: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Whiteboard friendly

Allison

Ally’sBlog

OWNS

26Donnerstag, 27. Oktober 2011

Page 50: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Whiteboard friendly

Allison

Ally’sBlog

BlogPost

BlogPost 2

OWNS

WRO

TE

WROTE

BELONGS_TO

BELONGS_TO

26Donnerstag, 27. Oktober 2011

Page 51: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Whiteboard friendly

Allison

Ally’sBlog

BlogPost

BlogPost 2

Comment

Comment

OWNS

WRO

TE

WROTE

BELONGS_TO

BELONGS_TO

COMMENT_FORCO

MM

ENT_

FOR

26Donnerstag, 27. Oktober 2011

Page 52: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Whiteboard friendly

Allison

Ally’sBlog

BlogPost

BlogPost 2

Comment

Comment

OWNS

WRO

TE

WROTE

BELONGS_TO

BELONGS_TO

COMMENT_FORCO

MM

ENT_

FOR

26Donnerstag, 27. Oktober 2011

Page 53: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Show me some code, please

Node david = graphDb.createNode();Node andreas = graphDb.createNode();

david.setProperty(“name”, “David Montag”);andreas.setProperty(“name”, “Andreas Kollegger”);

Relationship presentedWith = david.createRelationshipTo( andreas, PresentationTypes.PRESENTED_WITH);presentedWith.setProperty(“date”, System.currentTimeMillis());

GraphDatabaseService graphDb = new EmbeddedGraphDatabase(“var/neo4j”);

27Donnerstag, 27. Oktober 2011

Page 54: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Show me some code, please

Node david = graphDb.createNode();Node andreas = graphDb.createNode();

david.setProperty(“name”, “David Montag”);andreas.setProperty(“name”, “Andreas Kollegger”);

Relationship presentedWith = david.createRelationshipTo( andreas, PresentationTypes.PRESENTED_WITH);presentedWith.setProperty(“date”, System.currentTimeMillis());

Transaction tx = graphDb.beginTx();try {

tx.success();} finally { tx.finish();}

GraphDatabaseService graphDb = new EmbeddedGraphDatabase(“var/neo4j”);

27Donnerstag, 27. Oktober 2011

Page 55: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Traversal framework

28Donnerstag, 27. Oktober 2011

Page 56: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Traversal frameworkExample: a dependency graph

A

BDC

28Donnerstag, 27. Oktober 2011

Page 57: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Traversal frameworkExample: a dependency graph

A

BDC

Query: Find all dependencies of A, transitively

28Donnerstag, 27. Oktober 2011

Page 58: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Traversal frameworkExample: a dependency graph

A

BDC

Query: Find all dependencies of A, transitively

28Donnerstag, 27. Oktober 2011

Page 59: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Traversal frameworkExample: a dependency graph

A

BDC

Query: Find all dependencies of A, transitively

28Donnerstag, 27. Oktober 2011

Page 60: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Traversal frameworkExample: a dependency graph

A

BDC

Query: Find all dependencies of A, transitively

28Donnerstag, 27. Oktober 2011

Page 61: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Traversal frameworkExample: a dependency graph

A

BDC

Query: Find all dependencies of A, transitively

TraversalDescription desc = Traversal.description() .relationships(ExampleTypes.DEPENDS_ON, Direction.OUTGOING);

Node a = ...;

for (Node dependency : desc.traverse(a).nodes()) { print(dependency);}

28Donnerstag, 27. Oktober 2011

Page 62: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

So how do I find a node to traverse from?

?

29Donnerstag, 27. Oktober 2011

Page 63: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

So how do I find a node to traverse from?

?By us

ing in

dexin

g!

29Donnerstag, 27. Oktober 2011

Page 64: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

So how do I find a node to traverse from?

?name: DavidBy us

ing in

dexin

g!

29Donnerstag, 27. Oktober 2011

Page 65: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

So how do I find a node to traverse from?

?Davidname: DavidBy

using

inde

xing!

29Donnerstag, 27. Oktober 2011

Page 66: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

So how do I find a node to traverse from?

?Davidname: David

Ed

Allison

Michael

Andreas

By us

ing in

dexin

g!

29Donnerstag, 27. Oktober 2011

Page 67: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Cypher Query Language

๏Declarative query language

•Describe what you want, not how

•Based on pattern matching

๏Examples:

30

START david=node:people(name=”David M”) # index lookupMATCH david-[:knows]-()-[:knows]-foafWHERE foaf.age > 18RETURN foaf

START user=node(5, 15, 26, 28) # node IDsMATCH user--friendRETURN user, COUNT(friend), SUM(friend.money)

30Donnerstag, 27. Oktober 2011

Page 68: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Cypher Query Language

๏Declarative query language

•Describe what you want, not how

•Based on pattern matching

๏Examples:

30

START david=node:people(name=”David M”) # index lookupMATCH david-[:knows]-()-[:knows]-foafWHERE foaf.age > 18RETURN foaf

START user=node(5, 15, 26, 28) # node IDsMATCH user--friendRETURN user, COUNT(friend), SUM(friend.money)

(Experimental)

30Donnerstag, 27. Oktober 2011

Page 69: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Beyond basics๏Graph algorithm library

•Cheapest path (Dijkstra, A*)

• Shortest path

• Simple paths

•All paths

๏REST API access to Neo4j Standalone Server

๏High availability and online backups

• Provides fault tolerance and horizontal scaling of reads

31

31Donnerstag, 27. Oktober 2011

Page 70: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Spring Data Neo4j

32Donnerstag, 27. Oktober 2011

Page 71: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Spring Framework Conveniences

๏default enterprise development framework

๏ future Java Cloud stack

๏POJO centric application design

๏made AspectJ aspects socially acceptable (tx-config, @Configurable)

๏Template programming model

๏ Inversion of Control / Dependency Injection

๏Spring Java Config, configuration XML-namespaces

๏ lots of powerful libraries and library abstractions

๏existing, well-known persistence framework for JDBC

๏Spring Data project

33Donnerstag, 27. Oktober 2011

Page 72: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Programming model overview

๏SDN is the brain child of Rod Johnson and Emil Eifrém

•Wrote functional initial prototype

•Developed by Neo Technology and SpringSource teams

๏Uses annotations to define POJO entities

๏Entity state backed by graph database

๏Two modes of Object Graph Mapping

• Spring Data Mapping

• seamless object mapping leverages AspectJ

๏Spring Roo add-on available

34Donnerstag, 27. Oktober 2011

Page 73: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Spring Data Neo4j features

๏ Annotation-based programming model

๏ Spring Data Commons Repository support

๏ Neo4j Query (Cypher, Gremlin) and Traversal support

• on dynamic fields and via repository methods

๏ Neo4j indexing support (includes fulltext and numeric range queries)

๏ Entity types stored in the graph database as well

๏ Dynamic type projection (duck typing)

๏ Cross-store support for partial JPA / graph entities

๏ Support for JSR-303 (bean validation)

๏ Support for the Neo4j Server (remote server and in server extension)

๏ Neo4jTemplate with exception translation, optional transaction management and more

35

35Donnerstag, 27. Oktober 2011

Page 74: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

public class Actor { private final Node underlyingNode;

Actor( final Node node ) { underlyingNode = node; }

public Node getUnderlyingNode() { return underlyingNode; }

public final String getName() { return (String) underlyingNode.getProperty( “name” ); }

public void setName( final String name ) { underlyingNode.setProperty( “name”, name ); }}

Classic Neo4j domain class

36Donnerstag, 27. Oktober 2011

Page 75: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Spring Data Neo4j domain class@NodeEntitypublic class Actor {

@Indexed private String name;

public String getName() { return name; }

public void setName(String name) { this.name = name; }}

37Donnerstag, 27. Oktober 2011

Page 76: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

What about relationships

public Iterable<Movie> getMovies() { final List<Movie> movies = new LinkedList<Movie>(); for ( Relationship rel : underlyingNode.getRelationships( RelTypes.ACTS_IN, Direction.OUTGOING ) ) { movies.add( new Movie( rel.getEndNode() ) ); } return movies; }

@NodeEntityclass Actor { ...

Old @RelatedTo(type="ACTS_IN", elementCl

ass = Movie.class)

private Set<Movie> movies; public Iterable<Movie> getMovies() {

return movies; }

New

38Donnerstag, 27. Oktober 2011

Page 77: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Defining entity classes

39Donnerstag, 27. Oktober 2011

Page 78: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Defining entity classes

•@NodeEntity

• Represents a node in the graph

• Fields saved as properties on node

• References stored as relationships between nodes

• Instantiated using Java ‘new’ keyword, like any POJO

• Also returned by lookup mechanisms

• Type information stored in the graph

39Donnerstag, 27. Oktober 2011

Page 79: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Defining entity classes

40Donnerstag, 27. Oktober 2011

Page 80: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Defining entity classes

•@RelationshipEntity

• Represents a relationship in the graph

• Fields saved as properties on relationship

• Special fields for start- and end-nodes

• Only returned by lookup methods

40Donnerstag, 27. Oktober 2011

Page 81: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Fields in node entities (@NodeEntity)

• Primitive types and strings are directly persisted

• For all other types, Spring conversion support can be used

• Enum and Date conversion is provided out-of-the-box

•Transient fields not persisted

41

@NodeEntitypublic class Actor { private String name; private int age; private HairColor hairColor; private transient String nickname;}

41Donnerstag, 27. Oktober 2011

Page 82: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Fields in node entities (@NodeEntity)

• Fields of types that represent a node (@NodeEntity)

42

42Donnerstag, 27. Oktober 2011

Page 83: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Fields in node entities (@NodeEntity)

• Fields of types that represent a node (@NodeEntity)

42

@NodeEntitypublic class Movie {}

@NodeEntitypublic class Person { private Movie favoriteMovie;}

42Donnerstag, 27. Oktober 2011

Page 84: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Fields in node entities (@NodeEntity)

• Fields of types that represent a node (@NodeEntity)

42

@NodeEntitypublic class Movie {}

@NodeEntitypublic class Person { private Movie favoriteMovie;}

@NodeEntitypublic class Movie { private Actor topActor;}

@NodeEntitypublic class Actor { // Mirrors topActor in Movie @RelatedTo(type = ”topActor”, direction = Direction.INCOMING) private Movie wasTopActorIn;}

42Donnerstag, 27. Oktober 2011

Page 85: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Fields in node entities (@NodeEntity)

• Fields of collections of node entities: @RelatedTo

43

@NodeEntitypublic class Movie {}

@NodeEntitypublic class Actor { @RelatedTo(type = “ACTS_IN”) private Set<Movie> movies;}

43Donnerstag, 27. Oktober 2011

Page 86: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Fields in node entities (@NodeEntity)

๏Fields of collections of relationship entities: @RelatedToVia

๏Read only view of relationship entities44

@RelationshipEntitypublic class Role { @StartNode private Actor actor; @EndNode private Movie movie; private String roleName;}

@NodeEntitypublic class Actor { @RelatedToVia(type = “ACTS_IN”) private Iterable<Role> roles;}

44Donnerstag, 27. Oktober 2011

Page 87: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Fields in relationship entities (@RelationshipEntity)

• Primitive and convertible types work just the same

• @StartNode and @EndNode provide access to the start and end node entities for the relationship entity

@RelationshipEntitypublic class Role { @StartNode private Actor actor; @EndNode private Movie movie; private String title;}

45Donnerstag, 27. Oktober 2011

Page 88: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Indexing

@NodeEntitypublic class Actor { @Indexed private String name; @Indexed private HairColor hairColor;

GraphRepository<Actor> actorRepo = template.repositoryFor(Actor.class);Actor kevin = actorRepo.findByPropertyValue(“name”, “Kevin Bacon”);Iterable<Actor> allBlondActors = actorRepo.findAllByPropertyValue(“hairColor”, “blond”);

It can then be looked up:

By annotating an entity field with @Indexed it becomes searchable:

46Donnerstag, 27. Oktober 2011

Page 89: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Indexing

@NodeEntitypublic class Actor { @Indexed(type = FULLTEXT) private String name;

๏ Index name defaults to domain class name

๏ Index key defaults to field name

๏Fulltext and spatial index types

๏Repository query methods for any Lucene query, including ranges:

Iterable<Actor> allKevinsOlderThan32 = actorRepo.findAllByQuery(“name:Kevin* AND age>32”);Iterable<Actor> youngActors = actorRepo.findAllByRange(“age”, 3, 18);

47Donnerstag, 27. Oktober 2011

Page 90: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Traversal

48

@NodeEntitypublic class Actor { @GraphTraversal( traversalBuilder = CoactorsTraversalDescriptionBuilder.class) private Iterable<Actor> coactors;}

public class CoactorsTraversalDescriptionBuilder implements FieldTraversalDescriptionBuilder { public TraversalDescription build(...) { return Traversal.description() .evaluator(Evaluators.atDepth(2)) .relationships(RelTypes.ACTS_IN); }}

Example for dynamic field computation

48Donnerstag, 27. Oktober 2011

Page 91: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Cypher query language

49

@NodeEntitypublic class Actor { @Query(“START actor=({self}) ” + “MATCH (actor)-[:ACTS_IN]->(movie)<-[:ACTS_IN]-(coactor) ” + “RETURN coactor”) private Iterable<Actor> coactors;}

@NodeEntitypublic class Actor { @Query(“START actor=({self}) ” + “MATCH (actor)-[:ACTS_IN]->(movie)<-[:ACTS_IN]-(coactor) ” + “RETURN movie.title, coactor.name”) private Iterable<Map<String, Object>> movieCoactorPairs;}

49Donnerstag, 27. Oktober 2011

Page 92: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Spring-Data-Mapping

50

๏Based on Spring-Data-Commons infrastructure

• Extract Mapping Meta Information

‣Neo4jPersistentEntity, Neo4jPersistentProperty

• Entity-Converter Implementations for Object-Graph-Mapping

‣Type-resolution

‣Entity construction

‣Transfer properties

‣loaed for eagerly fetched relationships

•Neo4j-Template for Graph-Interaction

50Donnerstag, 27. Oktober 2011

Page 93: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

AspectJ

51

๏ Introduces interface to entities:

•NodeBacked into @NodeEntity classes

• RelationshipBacked into @RelationshipEntity classes

๏NodeBacked introduces methods such as:

• relateTo

• findByQuery

• findAllByTraversal

• ...

๏going to be pulled out in separate Active-Record-Mixin

51Donnerstag, 27. Oktober 2011

Page 94: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

AspectJ - Tooling

52

๏ IDE‘s

• latest versions of STS / Eclipse with current AJDT plugin

• IntelliJ IDEA 10.5 compile + run, some editor quirks

‣full AspectJ support in IDEA 11

๏Build Systems

•Maven

•Gradle

•Ant / Ivy

• ...

52Donnerstag, 27. Oktober 2011

Page 95: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

AspectJ - NodeBacked.relateTo

53

<T extends RelationshipBacked> T NodeBacked.relateTo( NodeBacked node, Class<T> relationshipEntityType, String relationshipType);

@NodeEntitypublic class Actor { public Role actsIn(Movie movie, String roleName) { Role role = relateTo(movie, Role.class, “ACTS_IN”); role.setName(roleName); return role; }}

usage:

53Donnerstag, 27. Oktober 2011

Page 96: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Interface based Repositories๏ based on Repository infrastructure in Spring Data Commons

๏ just define the interface and the namespace configuration

๏provide out-of-the-box support for

•CRUD-Operations

• Index-Lookups

•Traversal-Execution

•Graph-Queries (Cypher, Gremlin)

• derived Queries

• Spatial Queries

๏extensible via custom methods with provided implementations54

54Donnerstag, 27. Oktober 2011

Page 97: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Repositories

55

interface MovieRepository extends GraphRepository<Movie> { Movie findById(String id); Page<Movie> findByTitle(String title, Pageable page);}

<neo4j:repositories base-package=“com.example.repositories„/

@Controllerpublic class MovieController { @Autowired MovieRepository moviesRepository;

@RequestMapping(value = "/movies/{movieId}",...) public String show(Model model, @PathVariable String movieId) { Movie movie = moviesRepository.findByPropertyValue("id", movieId); Movie movie = moviesRepository.findById(movieId); model.addAttribute("movie", movie); return "/movies/show"; }}

55Donnerstag, 27. Oktober 2011

Page 98: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Other repository query methods

Iterable<Actor> allActors = actorRepo.findAll();

long numberOfActors = actorRepo.count();

Actor jeffGoldblum = actorRepo.findOne(42);

boolean actorExists = actorRepo.exists(42);

Iterable<Actor> actors = actorRepo.findAllByTraversal(movie,traversal);

Page<Actor> actors = actorRepo.findAll(new PageRequest(page, PAGE_SIZE));

Iterable<Actor> actorsByNameAndAge = actorRepo.findAll(new Sort(„name“,“age“));

56Donnerstag, 27. Oktober 2011

Page 99: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Repository-Query-Support

57

interface MovieRepository extends GraphRepository<Movie> {

@Query("start m=({movie}) match m-[ACTS_IN]-actor return actor") Iterable<Actor> getActorsCypher(@Param("movie") Movie m); @Query("start movie =({0}) match (movie)<-[role:ACTS_IN]-(actor) return actor.name, role.title") Iterable<Map<String,Object>> getCast(Movie m);

@Query(value = "g.v(movie).out('ACTS_IN')", type = QueryType.Gremlin) Iterable<Person> getActorsGremlin(@Param("movie") Movie m);}

57Donnerstag, 27. Oktober 2011

Page 100: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Neo4j-Template (I)

๏well known Spring Template Pattern

๏Resource / Transaction Management

๏Convenience Methods

๏Nodes and Entities handling & conversion

๏Fluent Query Result Handling

๏Works also via REST with Neo4j-Server

๏Exception Translation

58

58Donnerstag, 27. Oktober 2011

Page 101: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Neo4j-Template (II)

59

template.lookup("node", "name", "David") .to(String.class, new PropertyContainerNameConverter()).single()

template.traverse(node, traversal) .to(Integer.class,new ResultConverter<Path,Integer>() { public Integer convert(Path path, Class<String> type) { return path.length(); }})

template.query("start movie=(Movies,title, {m}) match movie-->actor return actor", map("m","Matrix")).to(Actor.class)

template.execute("g.v(ref).outE", map("ref",0)).to(Relationship.class)

59Donnerstag, 27. Oktober 2011

Page 102: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

REST-Client-Support

60

<bean id="restGraphDatabaseService" class="org.sf.data.neo4j.rest.SpringRestGraphDatabase"> <constructor-arg value="http://localhost:7473/db/data" /> </bean>

<datagraph:config graphDatabaseService="restGraphDatabaseService"/>

๏drop-in replacement for the embedded GraphDatabase

๏works transparently with POJO-Entity-Mapping and

Neo4j-Template

60Donnerstag, 27. Oktober 2011

Page 103: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

REST-Server-Support

61

public class HelloWorldInitializer extends SpringPluginInitializer { public HelloWorldInitializer() { super(new String[]{"spring/helloWorldServer-Context.xml"}, Pair.of("worldRepository", WorldRepository.class), Pair.of("graphRepositoryFactory", GraphRepositoryFactory.class)); }}

๏ integrate Spring Data Neo4j config with already running

Graph-Database in Neo4j-Server

๏expose Spring Beans as Jersey Injectables

61Donnerstag, 27. Oktober 2011

Page 104: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Cross-store persistence

62Donnerstag, 27. Oktober 2011

Page 105: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

A scenario...

You have a traditional web app using JPA to persist data to a relational database

63Donnerstag, 27. Oktober 2011

Page 106: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Option C: Introducing cross-store persistence

๏ JPA data and NOSQL data can share a data model

๏Could be the entire entity, or some fields of an entity

๏We call this cross-store persistence

•One transaction manager to coordinate the NOSQL database with the JPA relational database

•AspectJ support to manage the NOSQL entities and fields

64Donnerstag, 27. Oktober 2011

Page 107: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

The JPA data model

Restaurant@Entitypublic class Restaurant {

@Id @GeneratedValue private Long id; private String name; private String city; private String state; private String zipCode;

UserAccount@Entity@Table(name = "user_account")public class UserAccount { @Id @GeneratedValue private Long id; private String userName; private String firstName; private String lastName; @Temporal(TemporalType.TIMESTAMP) private Date birthDate; @ManyToMany(cascade = CascadeType.ALL) private Set<Restaurant> favorites;

65Donnerstag, 27. Oktober 2011

Page 108: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Adding to the data model

Recommendation

@RelationshipEntitypublic class Recommendation { @StartNode private UserAccount user; @EndNode private Restaurant restaurant; private int stars; private String comment;

Restaurant@Entity@NodeEntity(partial = true)public class Restaurant { @Id @GeneratedValue private Long id; private String name; private String city; private String state; private String zipCode;

UserAccount@Entity@Table(name = "user_account")@NodeEntity(partial = true)public class UserAccount { @Id @GeneratedValue private Long id; private String userName; private String firstName; private String lastName; @Temporal(TemporalType.TIMESTAMP) private Date birthDate; @ManyToMany(cascade = CascadeType.ALL) private Set<Restaurant> favorites;

@GraphProperty String nickname; @RelatedTo(type = "friends", elementClass = UserAccount.class) Set<UserAccount> friends; @RelatedToVia(type = "recommends", elementClass = Recommendation.class) Iterable<Recommendation> recommendations;

66Donnerstag, 27. Oktober 2011

Page 109: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Adding to the data model

Recommendation

@RelationshipEntitypublic class Recommendation { @StartNode private UserAccount user; @EndNode private Restaurant restaurant; private int stars; private String comment;

Restaurant@Entity@NodeEntity(partial = true)public class Restaurant { @Id @GeneratedValue private Long id; private String name; private String city; private String state; private String zipCode;

UserAccount@Entity@Table(name = "user_account")@NodeEntity(partial = true)public class UserAccount { @Id @GeneratedValue private Long id; private String userName; private String firstName; private String lastName; @Temporal(TemporalType.TIMESTAMP) private Date birthDate; @ManyToMany(cascade = CascadeType.ALL) private Set<Restaurant> favorites;

@GraphProperty String nickname; @RelatedTo(type = "friends", elementClass = UserAccount.class) Set<UserAccount> friends; @RelatedToVia(type = "recommends", elementClass = Recommendation.class) Iterable<Recommendation> recommendations;

66Donnerstag, 27. Oktober 2011

Page 110: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Adding to the data model

Recommendation

@RelationshipEntitypublic class Recommendation { @StartNode private UserAccount user; @EndNode private Restaurant restaurant; private int stars; private String comment;

Restaurant@Entity@NodeEntity(partial = true)public class Restaurant { @Id @GeneratedValue private Long id; private String name; private String city; private String state; private String zipCode;

UserAccount@Entity@Table(name = "user_account")@NodeEntity(partial = true)public class UserAccount { @Id @GeneratedValue private Long id; private String userName; private String firstName; private String lastName; @Temporal(TemporalType.TIMESTAMP) private Date birthDate; @ManyToMany(cascade = CascadeType.ALL) private Set<Restaurant> favorites;

@GraphProperty String nickname; @RelatedTo(type = "friends", elementClass = UserAccount.class) Set<UserAccount> friends; @RelatedToVia(type = "recommends", elementClass = Recommendation.class) Iterable<Recommendation> recommendations;

66Donnerstag, 27. Oktober 2011

Page 111: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Adding to the data model

Recommendation

@RelationshipEntitypublic class Recommendation { @StartNode private UserAccount user; @EndNode private Restaurant restaurant; private int stars; private String comment;

Restaurant@Entity@NodeEntity(partial = true)public class Restaurant { @Id @GeneratedValue private Long id; private String name; private String city; private String state; private String zipCode;

UserAccount@Entity@Table(name = "user_account")@NodeEntity(partial = true)public class UserAccount { @Id @GeneratedValue private Long id; private String userName; private String firstName; private String lastName; @Temporal(TemporalType.TIMESTAMP) private Date birthDate; @ManyToMany(cascade = CascadeType.ALL) private Set<Restaurant> favorites;

@GraphProperty String nickname; @RelatedTo(type = "friends", elementClass = UserAccount.class) Set<UserAccount> friends; @RelatedToVia(type = "recommends", elementClass = Recommendation.class) Iterable<Recommendation> recommendations;

66Donnerstag, 27. Oktober 2011

Page 112: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Adding to the data model

Recommendation

@RelationshipEntitypublic class Recommendation { @StartNode private UserAccount user; @EndNode private Restaurant restaurant; private int stars; private String comment;

Restaurant@Entity@NodeEntity(partial = true)public class Restaurant { @Id @GeneratedValue private Long id; private String name; private String city; private String state; private String zipCode;

UserAccount@Entity@Table(name = "user_account")@NodeEntity(partial = true)public class UserAccount { @Id @GeneratedValue private Long id; private String userName; private String firstName; private String lastName; @Temporal(TemporalType.TIMESTAMP) private Date birthDate; @ManyToMany(cascade = CascadeType.ALL) private Set<Restaurant> favorites;

@GraphProperty String nickname; @RelatedTo(type = "friends", elementClass = UserAccount.class) Set<UserAccount> friends; @RelatedToVia(type = "recommends", elementClass = Recommendation.class) Iterable<Recommendation> recommendations;

66Donnerstag, 27. Oktober 2011

Page 113: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Spring Data Neo4j Roo add-on

67

๏Roo adding support for non-JPA persistence providers

๏Spring Data Neo4j was the first NOSQL persistence Roo Add-On

๏See the chapter on Spring Data Neo4j in the latest O’Reilly Roo book, Getting Started with Roo.

67Donnerstag, 27. Oktober 2011

Page 114: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Spring Data Neo4j Roo add-on

68

roo> project --topLevelPackage org.neo4j.imdbroo> graph setup --provider NEO4J --databaseLocation target/imdb

roo> graph entity --class ~.model.Movieroo> field string titleroo> field number --fieldName year --type java.lang.Integer --permitReservedWords --primitive

roo> graph entity --class ~.model.Actorroo> field string name

roo> graph relationship --to Movie --from Actor --fieldName movies --type ACTS_IN --cardinality ONE_TO_MANYroo> graph relationship --via ~.model.Role --to Movie --from Actor --fieldName roles --type ACTS_IN --cardinality ONE_TO_MANYroo> graph relationship --from Movie --to Actor --type ACTS_IN --fieldName actors --direction INCOMING --cardinality MANY_TO_ONEroo> field string --fieldName title --class ~.model.Role

roo> controller scaffold --class ~.web.ActorController --entity ~.model.Actorroo> controller scaffold --class ~.web.MovieController --entity ~.model.Movie

68Donnerstag, 27. Oktober 2011

Page 115: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Spring Data Neo4j Guidebook“Good Relationships”

๏Spring Data Neo4j comes with a great Guide Book, featuring:

• Forewords by Rod Johnson and Emil Eifrem

•An easy to read, narrative tutorial walkthrough for cineasts.net

•A comprehensive reference for all the details

•Check it out here: http://spring.neo4j.org/guide

69

“I’m excited about Spring Data Neo4j.... Spring Data Neo4j makes working with Neo4j amazingly easy, and therefore has the potential to make you more successful as a developer.”

Rod Johnson, founder of Spring

69Donnerstag, 27. Oktober 2011

Page 116: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

The end (and the beginning!)๏See the Spring Data Neo4j site for more info:

http://spring.neo4j.org

๏Check out the developer notes at GitHub:http://spring.neo4j.org/notes

๏Again, don’t miss our fantastic e-book on Spring Data Neo4j:http://spring.neo4j.org/guide

๏Spring Data Forum at http://spring.neo4j.org/discussions

๏All about Neo4j: http://neo4j.org

๏Neo4j videos and webinars: http://video.neo4j.org

70Donnerstag, 27. Oktober 2011

Page 117: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

Cineasts.net

Check Out: http://spring.neo4j.org/tutorial71Donnerstag, 27. Oktober 2011

Page 118: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

72

72Donnerstag, 27. Oktober 2011

Page 119: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

72

72Donnerstag, 27. Oktober 2011

Page 120: Introduction to Spring Data Neo4j - Whiteship's Eprilwhiteship.me/wp-content/uploads/2011/11/spring... · Spring Data Neo4j ๏Focus on Spring Data Neo4j ๏VMWare is collaborating

72

We are hiring!

You take the red pill and we show youhow deep the rabbit hole goes, depth first.

Q&AAlso:

72Donnerstag, 27. Oktober 2011