Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.
Neo4j for Java Developers
All about the „4j“
Michael.Hunger@Neo4j.org
(Michael)-[:WORKS_FOR]->(Neo4j)
michael@neo4j.org | @mesirii | github.com/jexp | jexp.de/blog
Michael Hunger - Community C...
• From Pain to Graph
• Graphs Are Everywhere
• For once no Java Haters
• Demo(s)!
• Q&A
Today‘s Entertainment
Once Upon A Time in Sweden
Once Upon a Time in Sweden
Solution
History of Neo4j
• 0.x ...
small embeddable persistent graph library
• 1.x ...
adding indexes, server, first stab of Cyphe...
(graphs)-[:ARE]->(everywhere)
Value from Data Relationships
Common Use Cases
Internal Applications
Master Data Management
Network and
IT Operations
Frau...
The Whiteboard Model Is the Physical Model
CAR
name: "Dan"
born: May 29, 1970
twitter: "@dan"
name: "Ann"
born: Dec 5, 1975
since:
Jan 10, 2011
brand: "Volvo"
model:...
Relational to Graph
Relational Graph
KNOWS
ANDREAS
TOBIAS
MICA
DELIA
Person FriendPerson-Friend
ANDREAS
DELIA
TOBIAS
MICA
Neo4j: All About Patterns
(:Person { name:"Dan"} ) -[:LOVES]-> (:Person { name:"Ann"} )
LOVES
Dan Ann
LABEL PROPERTY
NODE ...
Cypher: Find Patterns
MATCH (:Person { name:"Dan"} ) -[:LOVES]-> (love:Person) RETURN love
LOVES
Dan ?
LABEL
NODE NODE
LAB...
Demo
Neo4j from Java
Good Old Days
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j</artifactId>
<version>2.2.5</version>
</dependen...
Neo4j‘s Java API
GraphDatabaseService db = ...
Node dan= db.createNode(Person);
dan.setProperty("name","Dan");
Relationshi...
Neo4j is Transactional
GraphDatabaseService db = ...
try (Transaction tx = db.beginTx()) {
Node dan = ...
Node ann = ...
R...
Heavy Lifting - Demo
Extend Neo4j Server
Extend Neo4j Server
@Path( "/meta" )
public class MetaInfoResource {
@GET @Produces( MediaType.APPLICATION_JSON )
@Path( "...
Cypher from Java
Running Cypher from Java
query =
"MATCH (:Person {name:{name}})-[:LOVES]->(p)
RETURN p.name AS loved";
params = map("name"...
Running Cypher from Java - Remote
url = "http://.../db/data/transaction/commit";
query = "MATCH ... RETURN loved";
params ...
Connect via JDBC
conn = driver.connect("jdbc:neo4j://localhost:7474");
PreparedStatement ps = conn.prepareStatement("
MATC...
Database-Tools, ETL, BI-Tools
JVM Languages
Clojure - neocons
(ns neocons.docs.examples
(:require [clojurewerkz.neocons.rest :as nr]
[clojurewerkz.neocons.rest.cypher...
Scala (AnormCypher – Spark)
import org.anormcypher._
import org.apache.spark.graphx._
val dbConn = Neo4jREST("localhost", ...
Groovy – Batch-Import
@Grab('org.neo4j:neo4j:2.2.5')
import org.neo4j.graphdb.*
batch = BatchInserters.inserter(store,conf...
Convenient Object Graph Mapping
Spring Data Neo4j
@NodeEntity
class Person {
@GraphId Long id;
String name;
@Relationship(type="LOVES") Person loved;
}
in...
Spring Data Neo4j
@EnableNeo4jRepositories(basePackages="sample.repositories")
public class MyNeo4jConfiguration extends N...
Spring Data Neo4j
@RelationshipEntity(type="LOVES")
class Love {
@GraphId Long id;
@StartNode Person lover;
@EndNode Perso...
Demo(s)
The Sky is the Limit
Learn More
Thank You
Questions ? Books!
michael@neo4j.org
@mesirii
Using Neo4j from Java
Prochain SlideShare
Chargement dans…5
×

Using Neo4j from Java

5 417 vues

Publié le

There are many ways to use Neo4j from Java. In this talk I want to demonstrate different APIs and examples on how to build solutions on top of Neo4j using a Java based stack.

Publié dans : Données & analyses
  • Soyez le premier à commenter

Using Neo4j from Java

  1. 1. Neo4j for Java Developers All about the „4j“ Michael.Hunger@Neo4j.org
  2. 2. (Michael)-[:WORKS_FOR]->(Neo4j) michael@neo4j.org | @mesirii | github.com/jexp | jexp.de/blog Michael Hunger - Community Caretaker @Neo4j
  3. 3. • From Pain to Graph • Graphs Are Everywhere • For once no Java Haters • Demo(s)! • Q&A Today‘s Entertainment
  4. 4. Once Upon A Time in Sweden Once Upon a Time in Sweden
  5. 5. Solution
  6. 6. History of Neo4j • 0.x ... small embeddable persistent graph library • 1.x ... adding indexes, server, first stab of Cypher • 2.x ... ease of use, data-model, optional schema, cost based optimizer, import, Neo4j-Browser • 3.x … binary protocol, bytecode compiled queries, sharding
  7. 7. (graphs)-[:ARE]->(everywhere)
  8. 8. Value from Data Relationships Common Use Cases Internal Applications Master Data Management Network and IT Operations Fraud Detection Customer-Facing Applications Real-Time Recommendations Graph-Based Search Identity and Access Management
  9. 9. The Whiteboard Model Is the Physical Model
  10. 10. CAR name: "Dan" born: May 29, 1970 twitter: "@dan" name: "Ann" born: Dec 5, 1975 since: Jan 10, 2011 brand: "Volvo" model: "V70" Property Graph Model Nodes • The objects in the graph • Can have name-value properties • Can be labeled Relationships • Relate nodes by type and direction • Can have name-value properties LOVES LOVES LIVES WITH PERSON PERSON
  11. 11. Relational to Graph Relational Graph KNOWS ANDREAS TOBIAS MICA DELIA Person FriendPerson-Friend ANDREAS DELIA TOBIAS MICA
  12. 12. Neo4j: All About Patterns (:Person { name:"Dan"} ) -[:LOVES]-> (:Person { name:"Ann"} ) LOVES Dan Ann LABEL PROPERTY NODE NODE LABEL PROPERTY
  13. 13. Cypher: Find Patterns MATCH (:Person { name:"Dan"} ) -[:LOVES]-> (love:Person) RETURN love LOVES Dan ? LABEL NODE NODE LABEL PROPERTY ALIAS ALIAS
  14. 14. Demo
  15. 15. Neo4j from Java
  16. 16. Good Old Days <dependency> <groupId>org.neo4j</groupId> <artifactId>neo4j</artifactId> <version>2.2.5</version> </dependency>
  17. 17. Neo4j‘s Java API GraphDatabaseService db = ... Node dan= db.createNode(Person); dan.setProperty("name","Dan"); Relationship rel = dan.createRelationshipTo(ann,LOVES); rel.setProperty("how","very"); db.shutdown();
  18. 18. Neo4j is Transactional GraphDatabaseService db = ... try (Transaction tx = db.beginTx()) { Node dan = ... Node ann = ... Relationship rel = ... tx.success(); } db.shutdown();
  19. 19. Heavy Lifting - Demo
  20. 20. Extend Neo4j Server
  21. 21. Extend Neo4j Server @Path( "/meta" ) public class MetaInfoResource { @GET @Produces( MediaType.APPLICATION_JSON ) @Path( "/{node}" ) public Response meta(@PathParam("node") long id, @Context GraphDatabaseService db) { Iterable labels = db.getNodeById(id).getLabels(); return Response.status( OK ).entity( labels ).build(); } }
  22. 22. Cypher from Java
  23. 23. Running Cypher from Java query = "MATCH (:Person {name:{name}})-[:LOVES]->(p) RETURN p.name AS loved"; params = map("name", "Dan"); try (result = db.execute(query, params)) { for (Map row : result) { row.get("loved"); } }
  24. 24. Running Cypher from Java - Remote url = "http://.../db/data/transaction/commit"; query = "MATCH ... RETURN loved"; params = map("name", "Dan"); r = HTTP.POST(url,"{statements: [{statement:query, parameters:params}]}") r.status() == 200 r.content().get("errors") == [] r.content().get("results").get(0) == [{"columns":["loved"],"data": [{"row": ["Ann"]}]}]
  25. 25. Connect via JDBC conn = driver.connect("jdbc:neo4j://localhost:7474"); PreparedStatement ps = conn.prepareStatement(" MATCH (:Person {name:{1}})-[:LOVES]->(loved) RETURN loved.name as loved"); ps.setLong(1,"Dan"); ResultSet rs = ps.executeQuery(); while (rs.next()) { rs.getString("loved"); }
  26. 26. Database-Tools, ETL, BI-Tools
  27. 27. JVM Languages
  28. 28. Clojure - neocons (ns neocons.docs.examples (:require [clojurewerkz.neocons.rest :as nr] [clojurewerkz.neocons.rest.cypher :as cy])) (defn -main [& args] (nr/connect! "http://host:port/db/data/") (let [query "MATCH (:Person {name:{name}})-[:LOVES]->(loved) RETURN lover.name as loved" res (cy/tquery query {:name "Dan"})] (println res)))
  29. 29. Scala (AnormCypher – Spark) import org.anormcypher._ import org.apache.spark.graphx._ val dbConn = Neo4jREST("localhost", 7474, "/db/data/") val q = """MATCH (p1:Page)-[:Link]->(p2) RETURN id(p1) AS from, id(p2) AS to LIMIT 100000000""" val r = Cypher(q).apply()(dbConn) val links = sc.parallelize(r,100).map( Edge(row[Int]("from").toLong,row[Int]("to").toLong, None)) links.count
  30. 30. Groovy – Batch-Import @Grab('org.neo4j:neo4j:2.2.5') import org.neo4j.graphdb.* batch = BatchInserters.inserter(store,config) for (line in parseCsv(csv)) { author = batch.createNode([name:line.author],Labels.Author) article= batch.createNode( [title:line.title, date:date],Labels.Article) batch.createRelationship(author,article, WROTE, NO_PROPS) } batch.createDeferredSchemaIndex(Labels.Article) .on("title").create()
  31. 31. Convenient Object Graph Mapping
  32. 32. Spring Data Neo4j @NodeEntity class Person { @GraphId Long id; String name; @Relationship(type="LOVES") Person loved; } interface PersonRepository extends GraphRepository<Person> { @Query("MATCH ... RETURN loved") Set<Person> findLoved(String person) }
  33. 33. Spring Data Neo4j @EnableNeo4jRepositories(basePackages="sample.repositories") public class MyNeo4jConfiguration extends Neo4jConfiguration { @Bean public Neo4jServer neo4jServer() { return new RemoteServer(System.getenv("NEO4J_URL")); } @Bean public SessionFactory getSessionFactory() { return new SessionFactory("sample.domain"); } }
  34. 34. Spring Data Neo4j @RelationshipEntity(type="LOVES") class Love { @GraphId Long id; @StartNode Person lover; @EndNode Person loved; Date since; }
  35. 35. Demo(s)
  36. 36. The Sky is the Limit
  37. 37. Learn More
  38. 38. Thank You Questions ? Books! michael@neo4j.org @mesirii

×