Spring Data Neo4j Intro SpringOne 2011
Upcoming SlideShare
Loading in...5
×
 

Spring Data Neo4j Intro SpringOne 2011

on

  • 1,819 views

Spring Data Graph is an integration library for the open source graph database Neo4j and has been around for over a year, evolving from its infancy as brainchild of Rod Johnson and Emil Eifrem. It ...

Spring Data Graph is an integration library for the open source graph database Neo4j and has been around for over a year, evolving from its infancy as brainchild of Rod Johnson and Emil Eifrem. It supports transparent AspectJ based POJO to Graph Mapping, a Neo4jTemplate API and extensive support for Spring Data Repositories. It can work with an embedded graph database or with the standalone Neo4j Server.

The session starts with a short introduction to graph databases. Following that, the different approaches using Spring Data Graph are explored in the Cineasts.net web-app, a social movie database which is also the application of the tutorial in the Spring Data Graph Guidebook. The session will also cover creating a green-field project using the Spring Roo Addon for Spring Data Graph and deploying the App to CloudFoundry.

Statistics

Views

Total Views
1,819
Views on SlideShare
1,817
Embed Views
2

Actions

Likes
3
Downloads
61
Comments
0

2 Embeds 2

http://www.linkedin.com 1
https://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • social networks (our actions in them work life health)\nthe internet\nits hardware\nits software\nour interactions\nour body\nnature environment\npolitical economic networks\nzusammenhaenge\nhistory\nscience\nzeit grünen abgeordneter handy\n
  • social networks (our actions in them work life health)\nthe internet\nits hardware\nits software\nour interactions\nour body\nnature environment\npolitical economic networks\nzusammenhaenge\nhistory\nscience\nzeit grünen abgeordneter handy\n
  • messy world\nfast changing world\nbez um graph sind teil der daten\nim rdbms teil des starren schemas\nkomplexe zusammenhaenge\nkomplexe fragen\nimmer neue kategorien - rels\ndynamisch - traversals\ntags attribute\ntemporale attribute\ndyn sprachen besser geeignet \n
  • messy world\nfast changing world\nbez um graph sind teil der daten\nim rdbms teil des starren schemas\nkomplexe zusammenhaenge\nkomplexe fragen\nimmer neue kategorien - rels\ndynamisch - traversals\ntags attribute\ntemporale attribute\ndyn sprachen besser geeignet \n
  • messy world\nfast changing world\nbez um graph sind teil der daten\nim rdbms teil des starren schemas\nkomplexe zusammenhaenge\nkomplexe fragen\nimmer neue kategorien - rels\ndynamisch - traversals\ntags attribute\ntemporale attribute\ndyn sprachen besser geeignet \n
  • \n
  • \n
  • \n
  • \n
  • Neo4j is a graph database. \n\nNodes, rels, key-value props on nodes and rels.\n
  • Neo4j is a graph database. \n\nNodes, rels, key-value props on nodes and rels.\n
  • Neo4j is a graph database. \n\nNodes, rels, key-value props on nodes and rels.\n
  • Neo4j is a graph database. \n\nNodes, rels, key-value props on nodes and rels.\n
  • Neo4j is a graph database. \n\nNodes, rels, key-value props on nodes and rels.\n
  • Neo4j is a graph database. \n\nNodes, rels, key-value props on nodes and rels.\n
  • Neo4j is a graph database. \n\nNodes, rels, key-value props on nodes and rels.\n
  • Neo4j is a graph database. \n\nNodes, rels, key-value props on nodes and rels.\n
  • Neo4j is a graph database. \n\nNodes, rels, key-value props on nodes and rels.\n
  • Neo4j is a graph database. \n\nNodes, rels, key-value props on nodes and rels.\n
  • ... so like I’m a node, Thomas is a node, and there’s a PRESENTED_WITH relationship between us.\n
  • ... so like I’m a node, Thomas is a node, and there’s a PRESENTED_WITH relationship between us.\n
  • ... so like I’m a node, Thomas is a node, and there’s a PRESENTED_WITH relationship between us.\n
  • ... so like I’m a node, Thomas is a node, and there’s a PRESENTED_WITH relationship between us.\n
  • ... so like I’m a node, Thomas is a node, and there’s a PRESENTED_WITH relationship between us.\n
  • ... so like I’m a node, Thomas is a node, and there’s a PRESENTED_WITH relationship between us.\n
  • ... so like I’m a node, Thomas is a node, and there’s a PRESENTED_WITH relationship between us.\n
  • schema-free evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • evolve data separately\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Traversing is great, but it needs to start from somewhere. How do we find that place?\n
  • Traversing is great, but it needs to start from somewhere. How do we find that place?\n
  • Traversing is great, but it needs to start from somewhere. How do we find that place?\n
  • Traversing is great, but it needs to start from somewhere. How do we find that place?\n
  • Traversing is great, but it needs to start from somewhere. How do we find that place?\n
  • Traversing is great, but it needs to start from somewhere. How do we find that place?\n
  • Traversing is great, but it needs to start from somewhere. How do we find that place?\n
  • Traversing is great, but it needs to start from somewhere. How do we find that place?\n
  • \n
  • \n
  • \n
  • No need for persistence contexts or entity managers.\n\n
  • No need for persistence contexts or entity managers.\n\n
  • \n
  • Jumping right into code\n
  • \n
  • \n
  • \n
  • \n
  • Anonymous relationships\n
  • Anonymous relationships\n
  • Anonymous relationships\n
  • Anonymous relationships\n
  • Anonymous relationships\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • This does not apply to Neo4j.\nIn Neo4j, transactions MUST be used.\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

Spring Data Neo4j Intro SpringOne 2011 Spring Data Neo4j Intro SpringOne 2011 Presentation Transcript

  • Introduction to Spring Data Neo4jMichael Hunger
  • Me & You ? ๏ Me: Michael Hunger, Neo Technology • passionate software developer / Neo4j German Division • Spring Data Neo4j Project Lead • Neo4j Cloud Hosting • michael.hunger@neotechnology.com / @mesirii ๏ You: • NOSQL ? • Enterprise ? • Rich Domain ?
  • What‘s up?๏ NOSQL overview๏ Spring Data overview๏ Networks are everywhere๏ Graph Databases๏ Neo4j introduction๏ Spring Data Neo4j introduction 3
  • NOSQL overview 4
  • What does NOSQL stand for?
  • What does NOSQL stand for? It’s not “No to SQL”
  • What does NOSQL stand for? It’s not “No to SQL” It’s not “Never SQL”
  • What does NOSQL stand for? It’s not “No to SQL” It’s not “Never SQL” It’s “Not Only SQL”
  • 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.
  • Why NOSQL now?We have observed four trends:๏ 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
  • NOSQL categoriesWe see four main categories in the NOSQL space:
  • NOSQL categoriesWe see four main categories in the NOSQL space: Key-Value •Redis •Riak •Voldemort
  • NOSQL categoriesWe see four main categories in the NOSQL space: Column-family/ Key-Value BigTable •Redis •Riak •Cassandra •Voldemort •HBase
  • NOSQL categoriesWe see four main categories in the NOSQL space: Column-family/ Key-Value BigTable •Redis •Riak •Cassandra •Voldemort •HBase Document •MongoDB •CouchDB
  • NOSQL categoriesWe see four main categories in the NOSQL space: Column-family/ Key-Value BigTable •Redis •Riak •Cassandra •Voldemort •HBase Document Graph •Neo4j •MongoDB •InfiniteGraph •CouchDB •OrientDB •DEX
  • Scaling to size vs. Scaling to complexity Size Key-Value stores Bigtable clones Document databases Graph databases Complexity 8
  • Scaling to size vs. Scaling to complexity Size Key-Value stores Bigtable clones Document databases Graph databases Billions of nodes and relationships Complexity 8
  • Scaling to size vs. Scaling to complexity Size Key-Value stores Bigtable clones Document databases Graph databases Billions of nodes and relationships > 90% of use cases Complexity 8
  • Spring Data overview
  • What is Spring Data๏ 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 10
  • 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
  • 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
  • Graphs areeverywhere 13
  • Even in the Matrix - everything is a grpah Google Image Search: „graph OR network“ 14
  • 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
  • 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
  • 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
  • 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
  • Fowler & Christakis „Connected“ 19
  • New York Times R&D „Cascade“ 20
  • Deb Roy - MIT & Bluefin Labs „Birth of a Word“ TED Talk Researches Social Reactions to (Media) Events 21
  • Neo4j introduction
  • What is Neo4j? data model
  • What is Neo4j? data model A Graph Database
  • What is Neo4j? data model A Graph Database
  • What is Neo4j? data model A Graph Database
  • What is Neo4j? data model A Graph Database Node Node
  • What is Neo4j? data model A Graph Database Typed relationship Node Node
  • What is Neo4j? data model A Graph Database Node Typed relationship Node key: value key: value
  • For example
  • For example name: Oliver
  • For example name: Oliver name: Michael
  • For example WORKS_WITH project: spring-data name: Oliver name: Michael
  • For example WORKS_WITH project: spring-data name: Oliver name: Michael EM PL LIVES_IN OY E D_ BY city: Dresden company: VMware country: DE
  • For example name: Rod KN S OW OW S KN WORKS_WITH project: spring-data name: Oliver name: Michael EM PL LIVES_IN OY E D_ BY city: Dresden company: VMware country: DE
  • For example name: Rod KN S OW OW S KN WORKS_WITH project: spring-data name: Oliver name: Michael EM PL LIVES_IN S OY LIKE E D_ BY city: Dresdenfood: Chinese company: VMware country: DE
  • 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
  • Whiteboard friendly
  • Whiteboard friendly Ally’s Blog NS W O Allison
  • Whiteboard friendly Blog Post BEL ON GS _TO Ally’s Blog WROTE BE LO NG NS S_ W O OT Blog Allison WROTE Post 2
  • Whiteboard friendly Blog Post BEL ON GS _TO Ally’s Blog WROTE BE LO NG NS S_ W O T O Blog Allison WROTE Post 2 CO MM EN T_ OR FO R COMMENT_F Comment Comment
  • Whiteboard friendly Blog Post BEL ON GS _TO Ally’s Blog WROTE BE LO NG NS S_ W O T O Blog Allison WROTE Post 2 CO MM EN T_ OR FO R COMMENT_F Comment Comment
  • Show me some code, pleaseGraphDatabaseService graphDb = new EmbeddedGraphDatabase(“var/neo4j”);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());
  • Show me some code, pleaseGraphDatabaseService graphDb = new EmbeddedGraphDatabase(“var/neo4j”);Transaction tx = graphDb.beginTx();try { 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()); tx.success();} finally { tx.finish();}
  • Traversal framework
  • Traversal frameworkExample: a dependency graph A B D C
  • Traversal frameworkExample: a dependency graphQuery: Find all dependencies of A, transitively A B D C
  • Traversal frameworkExample: a dependency graphQuery: Find all dependencies of A, transitively A B D C
  • Traversal frameworkExample: a dependency graphQuery: Find all dependencies of A, transitively A B D C
  • Traversal frameworkExample: a dependency graphQuery: Find all dependencies of A, transitively A B D C
  • Traversal frameworkExample: a dependency graphQuery: Find all dependencies of A, transitively A B D C TraversalDescription desc = Traversal.description() .relationships(ExampleTypes.DEPENDS_ON, Direction.OUTGOING); Node a = ...; for (Node dependency : desc.traverse(a).nodes()) { print(dependency); }
  • So how do I find a nodeto traverse from? ?
  • So how do I find a nodeto traverse from? g! in ex i nd i ng us B y ?
  • So how do I find a nodeto traverse from? g! in ex i nd i ng us B y name: David ?
  • So how do I find a nodeto traverse from? g! in ex i nd i ng us B y name: David ? David
  • So how do I find a nodeto traverse from? g! Andreas in ex i nd Michael i ng us B y name: David ? David Ed Allison
  • Cypher Query Language๏ Declarative query language • Describe what you want, not how • Based on pattern matching๏ Examples: START david=node:people(name=”David M”) # index lookup MATCH david-[:knows]-()-[:knows]-foaf WHERE foaf.age > 18 RETURN foaf START user=node(5, 15, 26, 28) # node IDs MATCH user--friend RETURN user, COUNT(friend), SUM(friend.money) 30
  • Cypher Query Language (E xp๏ Declarative query language en er ta im • Describe what you want, not how l) • Based on pattern matching๏ Examples: START david=node:people(name=”David M”) # index lookup MATCH david-[:knows]-()-[:knows]-foaf WHERE foaf.age > 18 RETURN foaf START user=node(5, 15, 26, 28) # node IDs MATCH user--friend RETURN user, COUNT(friend), SUM(friend.money) 30
  • 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
  • Spring Data Neo4j
  • 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
  • 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
  • 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
  • Classic Neo4j domain classpublic 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 ); }}
  • 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; }}
  • What about relationships@NodeEntityclass Actor { ... public Iterable <Movie> getMovi final List<Movi es() { e> movies = new for ( Relations LinkedList<Movi hip rel : under e>(); RelTypes.ACTS_I lyingNode.getRe N, Direction.OU lationships( movies.add( new TGOING ) ) { Movie( rel.getE Old } ndNode() ) ); return movies; } class) @RelatedTo(type="ACTS_ IN", elementClass = Movie. ; private Set<Movie> movies public Iterable<Movie> ge tMovies() { New return movies; }
  • Defining entity classes
  • 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
  • Defining entity classes
  • 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
  • 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 @NodeEntity public class Actor { private String name; private int age; private HairColor hairColor; private transient String nickname; } 41
  • Fields in node entities (@NodeEntity)• Fields of types that represent a node (@NodeEntity) 42
  • Fields in node entities (@NodeEntity)• Fields of types that represent a node (@NodeEntity) @NodeEntity public class Movie {} @NodeEntity public class Person { private Movie favoriteMovie; } 42
  • Fields in node entities (@NodeEntity)• Fields of types that represent a node (@NodeEntity) @NodeEntity public class Movie {} @NodeEntity public class Person { private Movie favoriteMovie; } @NodeEntity public class Movie { private Actor topActor; } @NodeEntity public class Actor { // Mirrors topActor in Movie @RelatedTo(type = ”topActor”, direction = Direction.INCOMING) private Movie wasTopActorIn; } 42
  • Fields in node entities (@NodeEntity)• Fields of collections of node entities: @RelatedTo @NodeEntity public class Movie {} @NodeEntity public class Actor { @RelatedTo(type = “ACTS_IN”) private Set<Movie> movies; } 43
  • Fields in node entities (@NodeEntity)๏ Fields of collections of relationship entities: @RelatedToVia @RelationshipEntity public class Role { @StartNode private Actor actor; @EndNode private Movie movie; private String roleName; } @NodeEntity public class Actor { @RelatedToVia(type = “ACTS_IN”) private Iterable<Role> roles; }๏ Read only view of relationship entities 44
  • 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 @RelationshipEntity public class Role { @StartNode private Actor actor; @EndNode private Movie movie; private String title; }
  • IndexingBy annotating an entity field with @Indexed it becomes searchable: @NodeEntity public class Actor { @Indexed private String name; @Indexed private HairColor hairColor;It can then be looked up: GraphRepository<Actor> actorRepo = template.repositoryFor(Actor.class); Actor kevin = actorRepo.findByPropertyValue(“name”, “Kevin Bacon”); Iterable<Actor> allBlondActors = actorRepo.findAllByPropertyValue(“hairColor”, “blond”);
  • Indexing @NodeEntity public 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);
  • Traversal@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 48
  • Cypher query language@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;} 49
  • Spring-Data-Mapping ๏ 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 50
  • AspectJ ๏ 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 51
  • AspectJ - Tooling ๏ 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 • ... 52
  • AspectJ - NodeBacked.relateTo<T extends RelationshipBacked> T NodeBacked.relateTo( NodeBacked node, Class<T> relationshipEntityType, String relationshipType);usage:@NodeEntitypublic class Actor { public Role actsIn(Movie movie, String roleName) { Role role = relateTo(movie, Role.class, “ACTS_IN”); role.setName(roleName); return role; }} 53
  • 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 implementations 54
  • Repositoriesinterface 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"; }} 55
  • Other repository query methodsActor jeffGoldblum = actorRepo.findOne(42);boolean actorExists = actorRepo.exists(42);Iterable<Actor> actors = actorRepo.findAllByTraversal(movie,traversal);Iterable<Actor> allActors = actorRepo.findAll();long numberOfActors = actorRepo.count();Page<Actor> actors = actorRepo.findAll(new PageRequest(page, PAGE_SIZE));Iterable<Actor> actorsByNameAndAge = actorRepo.findAll(new Sort(„name“,“age“));
  • Repository-Query-Supportinterface 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);} 57
  • 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
  • Neo4j-Template (II)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) 59
  • REST-Client-Support <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 60
  • REST-Server-Supportpublic 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 61
  • Cross-store persistence
  • A scenario...You have a traditional web app using JPA to persist data to a relational database
  • 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 managerdatabase the NOSQL database with the JPA relational to coordinate • AspectJ support to manage the NOSQL entities and fields
  • The JPA data model Restaurant UserAccount @Entity @Entity public class Restaurant { @Table(name = "user_account") @Id @GeneratedValue public class UserAccount { private Long id; @Id @GeneratedValue private String name; private Long id; private String city; private String userName; private String state; private String firstName; private String zipCode; private String lastName; @Temporal(TemporalType.TIMESTAMP) private Date birthDate; @ManyToMany(cascade = CascadeType.ALL) private Set<Restaurant> favorites;
  • Adding to the data model Restaurant UserAccount @Entity @Entity @NodeEntity(partial = true) @Table(name = "user_account") public class Restaurant { @NodeEntity(partial = true) @Id @GeneratedValue public class UserAccount { private Long id; @Id @GeneratedValue private String name; private Long id; private String city; private String userName; private String state; private String firstName; private String zipCode; private String lastName; @Temporal(TemporalType.TIMESTAMP) private Date birthDate; @ManyToMany(cascade = CascadeType.ALL) Recommendation private Set<Restaurant> favorites; @RelationshipEntity @GraphProperty public class Recommendation { String nickname; @StartNode @RelatedTo(type = "friends", private UserAccount user; elementClass = UserAccount.class) @EndNode Set<UserAccount> friends; private Restaurant restaurant; @RelatedToVia(type = "recommends", private int stars; elementClass = Recommendation.class) private String comment; Iterable<Recommendation> recommendations;
  • Adding to the data model Restaurant UserAccount @Entity @Entity @NodeEntity(partial = true) @Table(name = "user_account") public class Restaurant { @NodeEntity(partial = true) @Id @GeneratedValue public class UserAccount { private Long id; @Id @GeneratedValue private String name; private Long id; private String city; private String userName; private String state; private String firstName; private String zipCode; private String lastName; @Temporal(TemporalType.TIMESTAMP) private Date birthDate; @ManyToMany(cascade = CascadeType.ALL) Recommendation private Set<Restaurant> favorites; @RelationshipEntity @GraphProperty public class Recommendation { String nickname; @StartNode @RelatedTo(type = "friends", private UserAccount user; elementClass = UserAccount.class) @EndNode Set<UserAccount> friends; private Restaurant restaurant; @RelatedToVia(type = "recommends", private int stars; elementClass = Recommendation.class) private String comment; Iterable<Recommendation> recommendations;
  • Adding to the data model Restaurant UserAccount @Entity @Entity @NodeEntity(partial = true) @Table(name = "user_account") public class Restaurant { @NodeEntity(partial = true) @Id @GeneratedValue public class UserAccount { private Long id; @Id @GeneratedValue private String name; private Long id; private String city; private String userName; private String state; private String firstName; private String zipCode; private String lastName; @Temporal(TemporalType.TIMESTAMP) private Date birthDate; @ManyToMany(cascade = CascadeType.ALL) Recommendation private Set<Restaurant> favorites; @RelationshipEntity @GraphProperty public class Recommendation { String nickname; @StartNode @RelatedTo(type = "friends", private UserAccount user; elementClass = UserAccount.class) @EndNode Set<UserAccount> friends; private Restaurant restaurant; @RelatedToVia(type = "recommends", private int stars; elementClass = Recommendation.class) private String comment; Iterable<Recommendation> recommendations;
  • Adding to the data model Restaurant UserAccount @Entity @Entity @NodeEntity(partial = true) @Table(name = "user_account") public class Restaurant { @NodeEntity(partial = true) @Id @GeneratedValue public class UserAccount { private Long id; @Id @GeneratedValue private String name; private Long id; private String city; private String userName; private String state; private String firstName; private String zipCode; private String lastName; @Temporal(TemporalType.TIMESTAMP) private Date birthDate; @ManyToMany(cascade = CascadeType.ALL) Recommendation private Set<Restaurant> favorites; @RelationshipEntity @GraphProperty public class Recommendation { String nickname; @StartNode @RelatedTo(type = "friends", private UserAccount user; elementClass = UserAccount.class) @EndNode Set<UserAccount> friends; private Restaurant restaurant; @RelatedToVia(type = "recommends", private int stars; elementClass = Recommendation.class) private String comment; Iterable<Recommendation> recommendations;
  • Adding to the data model Restaurant UserAccount @Entity @Entity @NodeEntity(partial = true) @Table(name = "user_account") public class Restaurant { @NodeEntity(partial = true) @Id @GeneratedValue public class UserAccount { private Long id; @Id @GeneratedValue private String name; private Long id; private String city; private String userName; private String state; private String firstName; private String zipCode; private String lastName; @Temporal(TemporalType.TIMESTAMP) private Date birthDate; @ManyToMany(cascade = CascadeType.ALL) Recommendation private Set<Restaurant> favorites; @RelationshipEntity @GraphProperty public class Recommendation { String nickname; @StartNode @RelatedTo(type = "friends", private UserAccount user; elementClass = UserAccount.class) @EndNode Set<UserAccount> friends; private Restaurant restaurant; @RelatedToVia(type = "recommends", private int stars; elementClass = Recommendation.class) private String comment; Iterable<Recommendation> recommendations;
  • Spring Data Neo4j Roo add-on๏ 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. 67
  • Spring Data Neo4j Roo add-onroo> project --topLevelPackage org.neo4j.imdbroo> graph setup --provider NEO4J --databaseLocation target/imdbroo> graph entity --class ~.model.Movieroo> field string titleroo> field number --fieldName year --type java.lang.Integer --permitReservedWords --primitiveroo> graph entity --class ~.model.Actorroo> field string nameroo> 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.Roleroo> controller scaffold --class ~.web.ActorController --entity ~.model.Actorroo> controller scaffold --class ~.web.MovieController --entity ~.model.Movie 68
  • Spring Data Neo4j Guidebook “Good Relationships”“I’m excited about Spring Data Neo4j.... Spring Data Neo4j makes workingwith Neo4j amazingly easy, and therefore has the potential to make youmore successful as a developer.” Rod Johnson, founder of Spring๏ 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
  • 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
  • Cineasts.net Check Out: http://spring.neo4j.org/tutorial