(Neo4j)-[:          ]->Cypher
   Michael Hunger - Neo Technology


                                     1
(Michael) -[:WORKS_ON]-> (Neo4j)
                                         console


Cypher             community
                     graph
                                   Community

                     ME

Server


          Spring               Cloud


                                               2
3
is a


       4
NOSQL       Neo4j




        5
Graph Database




                 6
7
We're talking about a
Property Graph




                        7
We're talking about a
Property Graph


     Nodes




                        7
We're talking about a
Property Graph


     Nodes


      Relationships




                        7
We're talking about a
Property Graph
                                             Em                                       Joh
                                                  il                                      a   n
                                   knows                                     knows
                      Alli                                         Tob                                    Lar

     Nodes
                             son                                       ias           knows                   s
                                                           knows
                                           And                                       And                  knows
                      knows                      rea                                       rés
                                                       s
                                                           knows             knows                knows
                      Pet                                          Miic
                                                                   Mc                knows                 Ian
                         er                knows                        a
                                                                        a
                                   knows                   knows
                                            De                                       Mic
                                               lia                                      h   ael

      Relationships

             Properties (each a key+value)

        + Indexes (for easy look-ups)
                                                                                                                  7
7
8
(Neo4j) -[:IS_A]-> (Graph Database)
                                                                                                    Lucene
Sharding                                      1 M/s

        Master/
                                                                                         Index




                                                      LS
         Slave




                                              TRAVERSA
                          HIG
                                                                    TES
                              H_A
                                 VA                               RA
                                                                 G
                                    IL.                       TE
                                                           IN
                                                                   PROVIDES                        ACID
        Server     RUN
                       S_A                                        LI                                TX
                          S                                         CE
                                                                         NS
                                                                              ED
                                                                                   _L
                                    ES_T
 Ruby                                                                                 IK



                                                           RU
            JS                                                                           E
                                                                                                 MySQL
                      S
                    _A




                                                             NS
                                  SC AL

                                          O

Clojure


                                                             _O
                    NS




           .net
                  RU




                                                               N                             Mongo
                            34bn
     embedded                                                     Heroku
                            Nodes                                                                   9
How do you query this
  graph database?

                   10
With a Graph Query
     Language:
     Cypher


                 11
What is Cypher?
๏Pattern-Matching Query Language
๏Humane language
๏Expressive
๏Declarative: Say what you want, not how
๏borrows from well known query langs
๏Aggregation, Ordering, Limit
๏Update the Graph


                                           12
Something new? Why?
๏ Existing Neo4j query mechanisms were not simple enough
   • Too verbose (Java API)
   • Too prescriptive (Gremlin)
๏ SQL: Unable to express paths
   • these are crucial for graph-based reasoning
   • Neo4j is schema/table free
๏ SPARQL: designed for a different data model
   • namespaces
   • properties as nodes
                                                           13
A Graph
Can‘t see the Patterns for the Trees




               http://maxdemarzi.com/2012/02/13/visualizing-a-network-with-cypher/

                                                                      14
It‘s all about Patterns

                 A



             B       C

We want to find this Pattern!
                               15
Patterns in a Graph




                      16
17
18
19
20
Patterns as ASCII-ART




                   21
Patterns as ASCII-ART



   () --> ()
                   21
Named Nodes

 A      B




              22
Named Nodes

 A      B


(A) --> (B)

              22
Named Directed Rels
        LOVES
    A           B




                    23
Named Directed Rels
        LOVES
    A           B


   A -[:LOVES]-> B


                     23
Paths

A     B     C




                24
Paths

A     B     C


A --> B --> C

                24
Cyclic-Path-Patterns
          A



      B       C




                   25
Cyclic-Path-Patterns
           A



       B       C

A --> B --> C, A --> C

                     25
Cyclic-Path-Patterns
           A



       B       C

A --> B --> C, A --> C
 A --> B --> C <-- A
                     25
Variable Length Paths
        A     B

    A             B

A                      B

        ...
    A -[*]-> B        26
Optional Relationships

     A         B




                    27
Optional Relationships

     A         B

   A -[?]-> B

                    27
28
How does it work?




                    28
How does it work?




                    28
How does it work?
// lookup starting point in an index
start n=node:People(name = ‘Andreas’)




                        And
                              rea
                                    s




                                        28
How does it work?
// lookup starting point in an index
   then traverse to find results
start n=node:People(name = ‘Andreas’)
  match (n)--()--(foaf) return foaf




                        And
                              rea
                                    s




                                        28
28
The Parts of Cypher


                  29
30
Cypher: START + RETURN
๏ START <lookup> RETURN <expressions>
๏ START binds terms using simple look-up
   •directly using known ids
   •or based on indexed Property
๏ RETURN expressions specify result set




                                           30
Cypher: START + RETURN
๏ START <lookup> RETURN <expressions>
๏ START binds terms using simple look-up
   •directly using known ids
   •or based on indexed Property
๏ RETURN expressions specify result set
  // lookup node id 0, return that node
  start n=node(0) return n
  // lookup node in Index, return that node
  start n=node:Person(name="Andreas") return n
  // lookup all nodes, return all name properties
  start n=node(*) return n.name



                                                    30
31
Cypher: MATCH
๏ START <lookup> MATCH <pattern> RETURN <expr>
๏ MATCH describes a pattern of nodes+relationships
   •node terms in optional parenthesis
   •lines with arrows for relationships




                                                 31
Cypher: MATCH
๏ START <lookup> MATCH <pattern> RETURN <expr>
๏ MATCH describes a pattern of nodes+relationships
   •node terms in optional parenthesis
   •lines with arrows for relationships
 // lookup 'n', traverse any relationship to some 'm'
 start n=node(0) match (n)--(m) return n,m
 // any outgoing relationship from 'n' to 'm'
 start n=node(0) match n-->m return n,m
 // only 'KNOWS' relationships from 'n' to 'm'
 start n=node(0) match n-[:KNOWS]->m return n,m
 // from 'n' to 'm' and capture the relationship as 'r'
 start n=node(0) match n-[r]->m return n,r,m
 // from 'n' outgoing to 'm', then incoming from 'o'
 start n=node(0) match n-->m<--o return n,m,o
                                                          31
32
Cypher: RETURN
๏ RETURN <expressions>, aggregation(expr) as alias
๏ RETURN nodes, rels, properties
๏ RETURN expressions of functions and operators
๏ RETURN aggregation functions on the above




                                                  32
Cypher: RETURN
๏ RETURN <expressions>, aggregation(expr) as alias
๏ RETURN nodes, rels, properties
๏ RETURN expressions of functions and operators
๏ RETURN aggregation functions on the above


  // aggregate on n, count the m‘s
  start n=node(0) match n--m return n,count(*)
  // alias n.name as name
  start n=node(0) return n.name as name
  // aggregate m‘s into list
  start n=node(*) match n--m return n,collect(m)
  // filter m‘s by name
  start n=node(*) match n--m return n,filter(x in collect(m):
    m.name ˜= /A.*/) as a_block
                                                        32
33
Cypher: WHERE
๏ START <lookup> [MATCH <pattern>]
 WHERE <condition> RETURN <expr>
๏ WHERE filters nodes or relationships
   •uses expressions to constrain elements




                                             33
Cypher: WHERE
๏ START <lookup> [MATCH <pattern>]
 WHERE <condition> RETURN <expr>
๏ WHERE filters nodes or relationships
   •uses expressions to constrain elements
  // lookup all nodes as 'n', constrained to name 'Andreas'
  start n=node(*) where n.name='Andreas' return n
  // filter nodes where age is less than 30
  start n=node(*) where n.age<30 return n
  // filter using a regular expression
  start n=node(*) where n.name =~ /Tob.*/ return n
  // filter for a property exists
  start n=node(*) where has(n.name) return n



                                                        33
34
Cypher: CREATE
๏ CREATE <node>[,node or relationship] RETURN <expr>
  •create nodes with optional properties
  •create relationship (must have a type)




                                               34
Cypher: CREATE
๏ CREATE <node>[,node or relationship] RETURN <expr>
  •create nodes with optional properties
  •create relationship (must have a type)

 // create an anonymous node
 create n
 // create node with a property, returning it
 create n={name:'Andreas'} return n
 // lookup 2 nodes, then create a relationship and return it
 start n=node(0),m=node(1) create n-[r:KNOWS]-m return r
 // lookup nodes, then create a relationship with properties
 start n=node(1),m=node(2) create n-[r:KNOWS {since:2008}]->m



                                                       34
35
Cypher: CREATE UNIQUE
๏ CREATE UNIQUE node-[rel]->(node {prop : value})
   •„fixes“ the graph
   •starts at bound nodes, properties rels and nodes by
     comparing types and
                           tries to find


   •if not found creates them




                                                    35
Cypher: CREATE UNIQUE
๏ CREATE UNIQUE node-[rel]->(node {prop : value})
   •„fixes“ the graph
   •starts at bound nodes, properties rels and nodes by
     comparing types and
                           tries to find


   •if not found creates them
 // create a new relationship
 start n=.., m=.. create unique n-[:KNOWS]->m
 // create a new node AND relationship
 start n=... create unique n-[:TAGGED]->(tag {name:“neo“})
 // matches the tag node by name only creates new relationship
 start n=... create unique n-[:TAGGED]->(tag {name:“neo“})



                                                       35
36
Cypher: SET
๏ SET [<node property>] [<relationship property>]
   •update a property on a node or relationship
   •must follow a START




                                                    36
Cypher: SET
๏ SET [<node property>] [<relationship property>]
   •update a property on a node or relationship
   •must follow a START

  // update the name property
  start n=node(0) set n.name='Peter'
  // update many nodes, using a calculation
  start n=node(*) set n.size=n.size+1
  // match & capture a relationship, update a property
  start n=node(1) match n-[r]-m set r.times=10




                                                         36
37
Cypher: DELETE
๏ DELETE [<node>|<relationship>|<property>]
  •delete a node, relationship or property
  •toall relationships must be deleted first
      delete a node,




                                              37
Cypher: DELETE
๏ DELETE [<node>|<relationship>|<property>]
  •delete a node, relationship or property
  •toall relationships must be deleted first
      delete a node,



 // delete a node
 start n=node(5) delete n
 // remove a node and all relationships
 start n=node(3) match n-[r]-() delete n, r
 // remove a property
 start n=node(3) delete n.age




                                              37
More Advanced
  Examples

                38
START user = node(1)
                                           MATCH user -[user_skill]-> skill
                                           RETURN skill, user_skill
SELECT skills.*, user_skill.*
FROM users
JOIN user_skill ON users.id = user_skill.user_id
JOIN skills ON user_skill.skill_id = skill.id WHERE users.id = 1


                                                                   39
Example:
               Old, Influential Friends
START me = node(...)
MATCH (me) - [f:FRIEND] - (old_friend)
           - [:FRIEND ] - (fof)
WHERE ({today}-f.begin) > 365*10

WITH  old_friend, collect(fof.name) as names

WHERE    length(names) > 100
RETURN   old_friend, names
ORDER BY old_friend.name ASC
          f:FRIEND            :FRIEND
     me              friend             fof
Example:
                     Simple Recommendation
START me = node(...)
MATCH (me) -[r1:RATED   ]->(thing)
          <-[r2:RATED   ]- (someone)
           -[r3:RATED   ]->(cool_thing)
WHERE ABS(r1.stars-r2.stars) <= 2
       AND r3.stars > 3
RETURN cool_thing, count(*) AS cnt
ORDER BY cnt DESC LIMIT 10
          r1:RATED     thing   r2:RATED
     me                                       so
                                        TED
                               r   3: RA
                       cool
                       thing                   41
Cypher Cheat Sheet
             http://neo4j.org/resources/cypher




                                       42
The Rabbithole




                  http://console.neo4j.org
                 This Graph: http://tinyurl.com/7cnvmlq
                                             43
How to use Cypher
in YOUR programs

                44
Neo4j API
 ExecutionEngine engine = new ExecutionEngine(graphDB);


 String query = „start n=node:Person(name={name})
  match n-[:ACTS_IN]->movie<-[:ACTS_IN]-friend
  return friend“;
 ExecutionResult result = engine.query(query, map(„name“, „Keanu“);


 for (Map<String,Object> row : result) {
     Node friend = row.get(„friend“);
 }


 Iterator<Node> friends = result.columnAs(„friend“);




http://bit.ly/cypher-queries


                                                                  45
How to get started?




                      46
How to get started?
๏ Documentation




                      46
How to get started?
๏ Documentation
    • docs.neo4j.org - tutorials+reference




                                             46
How to get started?
๏ Documentation
    • docs.neo4j.org - tutorials+reference
    • http://console.neo4j.org




                                             46
How to get started?
๏ Documentation
    • docs.neo4j.org - tutorials+reference
    • http://console.neo4j.org
    • Neo4j in Action




                                             46
How to get started?
๏ Documentation
    • docs.neo4j.org - tutorials+reference
    • http://console.neo4j.org
    • Neo4j in Action
    • Good Relationships




                                             46
How to get started?
๏ Documentation
    • docs.neo4j.org - tutorials+reference
    • http://console.neo4j.org
    • Neo4j in Action
    • Good Relationships
๏ Get Neo4j




                                             46
How to get started?
๏ Documentation
    • docs.neo4j.org - tutorials+reference
    • http://console.neo4j.org
    • Neo4j in Action
    • Good Relationships
๏ Get Neo4j
    • http://neo4j.org/download




                                             46
How to get started?
๏ Documentation
    • docs.neo4j.org - tutorials+reference
    • http://console.neo4j.org
    • Neo4j in Action
    • Good Relationships
๏ Get Neo4j
    • http://neo4j.org/download
    • http://addons.heroku.com/neo4j/
๏ Participate
    • http://groups.google.com/group/neo4j
    • http://neo4j.meetup.com
                                             46
How to get started?
๏ Documentation
    • docs.neo4j.org - tutorials+reference
    • http://console.neo4j.org
    • Neo4j in Action
    • Good Relationships
๏ Get Neo4j
    • http://neo4j.org/download
    • http://addons.heroku.com/neo4j/
๏ Participate
    • http://groups.google.com/group/neo4j
    • http://neo4j.meetup.com
    • a session like this one ;)
                                             46
http://console.neo4j.org/r/GoT
https://dl.dropbox.com/u/14493611/got.txt
                                        47
Neo4j-JDBC Driver & MovieDB Dataset




http://blog.neo4j.org/2012/06/wanted-your-
       help-in-testing-neo4j-jdbc.html
                                             48
Got a Conference? Need a Dataset?




http://blog.neo4j.org/2012/08/at-conference-
          need-dataset-neo4j-at.html
                                           49
Neo4j in Action
Software Metrics


                   50
Graphs in Software Technolgoy
๏ UML Diagrams are graphs
๏ dependencies between classes, packages, modules etc are graphs
๏ Software Metrics use dependency analysis
๏ Visualizations
๏ Cyclomatic Complexity,
๏ Fan-in (afferent-coupling) / Fan-out (efferent coupling) etc.




                                                            51
Code City




            52
Class Diagram is a Graph




                           53
SonarJ




         54
But there is more
๏Visualize & query Method, Field
   dependencies
๏Collaborative filtering (co-usage)
๏Ranking
๏God classes
๏Paths between classes

                                     55
Welcome to Class-Graph
๏take a JAR
๏put it under ASM
๏scan it superfast
๏pull everything into Neo4j
๏add categories, indexes
๏Have Fun

     http://github.com/jexp/class-graph   56
Welcome to Class-Graph




                         57
Interactive Hands-On Session
๏Lots of tasks
๏use Cypher to solve them
   http://neo4j.org/resources/cypher
๏be creative, work together
๏ask !
๏Server http://bit.ly/innoq-neo4j
๏just the beginning
                                       58
Task: Find java.lang.Number and return it




                                            59
Task: Find java.lang.Number and return it


START o=node:types(name="java.lang.Number") 
RETURN o;




                                             59
Task: Subclasses of Number?




•Return just the name
•Order them alphabetically

                              60
Task: Subclasses of Number?


START n=node:types(name="java.lang.Number") 
 MATCH n<-[:SUPER_TYPE]-s
 RETURN s.name
 ORDER BY s.name;



•Return just the name
•Order them alphabetically

                                       60
Task: Which Methods does it have / how many




•Find the top 5 classes with the most members


                                                61
Task: Which Methods does it have / how many


START n=node:types(name="java.lang.Number") 
MATCH n-[:METHOD_OF|FIELD_OF]->m
RETURN m;




•Find the top 5 classes with the most members


                                                61
Task: Calculate the fan-out of
java.lang.StringBuilder




•Calculate fan-in
•Which class has the highest fan-out
•What about package-level?             62
Task: Calculate the fan-out of
 java.lang.StringBuilder
START o=node:types(name="j.l.StringBuilder")
MATCH o-[:FIELD_OF]->f-[:FIELD_TYPE]->tf,
      o-[:METHOD_OF]->m-[:PARAM_TYPE]->tp,
      m-[:RETURN_TYPE]->tr
RETURN o,count(distinct tf)
       + count(distinct tp)
       + count(distinct tr) as fan_out;

•Calculate fan-in
•Which class has the highest fan-out
•What about package-level?             62
Task: Find longest Inheritance Path




                                      63
Task: Find longest Inheritance Path


start c=node:types(name="java.lang.Object") 
match path=p<-[:SUPER_TYPE*]-c 
return extract(n in nodes(path) : n.name),
length(path) as len
order by len desc 
limit 5;




                                       63
Task: Find the class that used IOException
most often




                                             64
Task: Find the class that used IOException
most often

START ex=node:types(name="java.io.IOException"
MATCH ex<-[:THROWS]-m<-[:METHOD_OF]-c
RETURN c, count(*)
ORDER BY count(*)
LIMIT 5;




                                             64
Task: Which other classes did classes that
 threw IOException use most often?




•What could be a source of IOExceptions
                                              65
Task: Which other classes did classes that
 threw IOException use most often?
START ex=node:types(name="java.io.IOException")
MATCH ex<-[:THROWS]-m<-[:METHOD_OF]-c,
      mbr<-[:METHOD_OF|FIELD_OF]-c,
      mbr-[:FIELD_TYPE|PARAM_TYPE|
            RETURN_TYPE|THROWS]->other_type
WHERE other_type.name =~ /.+[.].+/
RETURN other_type.name, count(*)
ORDER BY count(*) desc
LIMIT 10;
•What could be a source of IOExceptions
                                              65
Task: Find a class you like and add a field with
your name and some type




                                            66
Task: Find a class you like and add a field with
 your name and some type
START c=node:types(name="void"),
 t=node:types(name="java.lang.reflect.Proxy") 
CREATE c-[:FIELD_OF]->(field {name:“Michael“})
       -[:FIELD_TYPE]->t;




                                             66
Task: Delete the most annoying class and all its
methods, fields and their relationships




                                           67
Task: Delete the most annoying class and all its
 methods, fields and their relationships
START c=node:types(name="java.awt.List"),
MATCH c-[r1:FIELD_OF|METHOD_OF]->mbr-[r2]-()
      c-[r]-()
DELETE c,mbr,r1,r2,r;




                                            67

Intro to Cypher

  • 1.
    (Neo4j)-[: ]->Cypher Michael Hunger - Neo Technology 1
  • 2.
    (Michael) -[:WORKS_ON]-> (Neo4j) console Cypher community graph Community ME Server Spring Cloud 2
  • 3.
  • 4.
  • 5.
    NOSQL Neo4j 5
  • 6.
  • 7.
  • 8.
    We're talking abouta Property Graph 7
  • 9.
    We're talking abouta Property Graph Nodes 7
  • 10.
    We're talking abouta Property Graph Nodes Relationships 7
  • 11.
    We're talking abouta Property Graph Em Joh il a n knows knows Alli Tob Lar Nodes son ias knows s knows And And knows knows rea rés s knows knows knows Pet Miic Mc knows Ian er knows a a knows knows De Mic lia h ael Relationships Properties (each a key+value) + Indexes (for easy look-ups) 7
  • 12.
  • 13.
  • 14.
    (Neo4j) -[:IS_A]-> (GraphDatabase) Lucene Sharding 1 M/s Master/ Index LS Slave TRAVERSA HIG TES H_A VA RA G IL. TE IN PROVIDES ACID Server RUN S_A LI TX S CE NS ED _L ES_T Ruby IK RU JS E MySQL S _A NS SC AL O Clojure _O NS .net RU N Mongo 34bn embedded Heroku Nodes 9
  • 15.
    How do youquery this graph database? 10
  • 16.
    With a GraphQuery Language: Cypher 11
  • 17.
    What is Cypher? ๏Pattern-MatchingQuery Language ๏Humane language ๏Expressive ๏Declarative: Say what you want, not how ๏borrows from well known query langs ๏Aggregation, Ordering, Limit ๏Update the Graph 12
  • 18.
    Something new? Why? ๏Existing Neo4j query mechanisms were not simple enough • Too verbose (Java API) • Too prescriptive (Gremlin) ๏ SQL: Unable to express paths • these are crucial for graph-based reasoning • Neo4j is schema/table free ๏ SPARQL: designed for a different data model • namespaces • properties as nodes 13
  • 19.
    A Graph Can‘t seethe Patterns for the Trees http://maxdemarzi.com/2012/02/13/visualizing-a-network-with-cypher/ 14
  • 20.
    It‘s all aboutPatterns A B C We want to find this Pattern! 15
  • 21.
    Patterns in aGraph 16
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
    Named Nodes A B (A) --> (B) 22
  • 30.
  • 31.
    Named Directed Rels LOVES A B A -[:LOVES]-> B 23
  • 32.
    Paths A B C 24
  • 33.
    Paths A B C A --> B --> C 24
  • 34.
  • 35.
    Cyclic-Path-Patterns A B C A --> B --> C, A --> C 25
  • 36.
    Cyclic-Path-Patterns A B C A --> B --> C, A --> C A --> B --> C <-- A 25
  • 37.
    Variable Length Paths A B A B A B ... A -[*]-> B 26
  • 38.
  • 39.
    Optional Relationships A B A -[?]-> B 27
  • 40.
  • 41.
    How does itwork? 28
  • 42.
    How does itwork? 28
  • 43.
    How does itwork? // lookup starting point in an index start n=node:People(name = ‘Andreas’) And rea s 28
  • 44.
    How does itwork? // lookup starting point in an index then traverse to find results start n=node:People(name = ‘Andreas’) match (n)--()--(foaf) return foaf And rea s 28
  • 45.
  • 46.
    The Parts ofCypher 29
  • 47.
  • 48.
    Cypher: START +RETURN ๏ START <lookup> RETURN <expressions> ๏ START binds terms using simple look-up •directly using known ids •or based on indexed Property ๏ RETURN expressions specify result set 30
  • 49.
    Cypher: START +RETURN ๏ START <lookup> RETURN <expressions> ๏ START binds terms using simple look-up •directly using known ids •or based on indexed Property ๏ RETURN expressions specify result set // lookup node id 0, return that node start n=node(0) return n // lookup node in Index, return that node start n=node:Person(name="Andreas") return n // lookup all nodes, return all name properties start n=node(*) return n.name 30
  • 50.
  • 51.
    Cypher: MATCH ๏ START<lookup> MATCH <pattern> RETURN <expr> ๏ MATCH describes a pattern of nodes+relationships •node terms in optional parenthesis •lines with arrows for relationships 31
  • 52.
    Cypher: MATCH ๏ START<lookup> MATCH <pattern> RETURN <expr> ๏ MATCH describes a pattern of nodes+relationships •node terms in optional parenthesis •lines with arrows for relationships // lookup 'n', traverse any relationship to some 'm' start n=node(0) match (n)--(m) return n,m // any outgoing relationship from 'n' to 'm' start n=node(0) match n-->m return n,m // only 'KNOWS' relationships from 'n' to 'm' start n=node(0) match n-[:KNOWS]->m return n,m // from 'n' to 'm' and capture the relationship as 'r' start n=node(0) match n-[r]->m return n,r,m // from 'n' outgoing to 'm', then incoming from 'o' start n=node(0) match n-->m<--o return n,m,o 31
  • 53.
  • 54.
    Cypher: RETURN ๏ RETURN<expressions>, aggregation(expr) as alias ๏ RETURN nodes, rels, properties ๏ RETURN expressions of functions and operators ๏ RETURN aggregation functions on the above 32
  • 55.
    Cypher: RETURN ๏ RETURN<expressions>, aggregation(expr) as alias ๏ RETURN nodes, rels, properties ๏ RETURN expressions of functions and operators ๏ RETURN aggregation functions on the above // aggregate on n, count the m‘s start n=node(0) match n--m return n,count(*) // alias n.name as name start n=node(0) return n.name as name // aggregate m‘s into list start n=node(*) match n--m return n,collect(m) // filter m‘s by name start n=node(*) match n--m return n,filter(x in collect(m): m.name ˜= /A.*/) as a_block 32
  • 56.
  • 57.
    Cypher: WHERE ๏ START<lookup> [MATCH <pattern>] WHERE <condition> RETURN <expr> ๏ WHERE filters nodes or relationships •uses expressions to constrain elements 33
  • 58.
    Cypher: WHERE ๏ START<lookup> [MATCH <pattern>] WHERE <condition> RETURN <expr> ๏ WHERE filters nodes or relationships •uses expressions to constrain elements // lookup all nodes as 'n', constrained to name 'Andreas' start n=node(*) where n.name='Andreas' return n // filter nodes where age is less than 30 start n=node(*) where n.age<30 return n // filter using a regular expression start n=node(*) where n.name =~ /Tob.*/ return n // filter for a property exists start n=node(*) where has(n.name) return n 33
  • 59.
  • 60.
    Cypher: CREATE ๏ CREATE<node>[,node or relationship] RETURN <expr> •create nodes with optional properties •create relationship (must have a type) 34
  • 61.
    Cypher: CREATE ๏ CREATE<node>[,node or relationship] RETURN <expr> •create nodes with optional properties •create relationship (must have a type) // create an anonymous node create n // create node with a property, returning it create n={name:'Andreas'} return n // lookup 2 nodes, then create a relationship and return it start n=node(0),m=node(1) create n-[r:KNOWS]-m return r // lookup nodes, then create a relationship with properties start n=node(1),m=node(2) create n-[r:KNOWS {since:2008}]->m 34
  • 62.
  • 63.
    Cypher: CREATE UNIQUE ๏CREATE UNIQUE node-[rel]->(node {prop : value}) •„fixes“ the graph •starts at bound nodes, properties rels and nodes by comparing types and tries to find •if not found creates them 35
  • 64.
    Cypher: CREATE UNIQUE ๏CREATE UNIQUE node-[rel]->(node {prop : value}) •„fixes“ the graph •starts at bound nodes, properties rels and nodes by comparing types and tries to find •if not found creates them // create a new relationship start n=.., m=.. create unique n-[:KNOWS]->m // create a new node AND relationship start n=... create unique n-[:TAGGED]->(tag {name:“neo“}) // matches the tag node by name only creates new relationship start n=... create unique n-[:TAGGED]->(tag {name:“neo“}) 35
  • 65.
  • 66.
    Cypher: SET ๏ SET[<node property>] [<relationship property>] •update a property on a node or relationship •must follow a START 36
  • 67.
    Cypher: SET ๏ SET[<node property>] [<relationship property>] •update a property on a node or relationship •must follow a START // update the name property start n=node(0) set n.name='Peter' // update many nodes, using a calculation start n=node(*) set n.size=n.size+1 // match & capture a relationship, update a property start n=node(1) match n-[r]-m set r.times=10 36
  • 68.
  • 69.
    Cypher: DELETE ๏ DELETE[<node>|<relationship>|<property>] •delete a node, relationship or property •toall relationships must be deleted first delete a node, 37
  • 70.
    Cypher: DELETE ๏ DELETE[<node>|<relationship>|<property>] •delete a node, relationship or property •toall relationships must be deleted first delete a node, // delete a node start n=node(5) delete n // remove a node and all relationships start n=node(3) match n-[r]-() delete n, r // remove a property start n=node(3) delete n.age 37
  • 71.
    More Advanced Examples 38
  • 72.
    START user =node(1) MATCH user -[user_skill]-> skill RETURN skill, user_skill SELECT skills.*, user_skill.* FROM users JOIN user_skill ON users.id = user_skill.user_id JOIN skills ON user_skill.skill_id = skill.id WHERE users.id = 1 39
  • 73.
    Example: Old, Influential Friends START me = node(...) MATCH (me) - [f:FRIEND] - (old_friend) - [:FRIEND ] - (fof) WHERE ({today}-f.begin) > 365*10 WITH  old_friend, collect(fof.name) as names WHERE length(names) > 100 RETURN old_friend, names ORDER BY old_friend.name ASC f:FRIEND :FRIEND me friend fof
  • 74.
    Example: Simple Recommendation START me = node(...) MATCH (me) -[r1:RATED ]->(thing) <-[r2:RATED ]- (someone) -[r3:RATED ]->(cool_thing) WHERE ABS(r1.stars-r2.stars) <= 2 AND r3.stars > 3 RETURN cool_thing, count(*) AS cnt ORDER BY cnt DESC LIMIT 10 r1:RATED thing r2:RATED me so TED r 3: RA cool thing 41
  • 75.
    Cypher Cheat Sheet http://neo4j.org/resources/cypher 42
  • 76.
    The Rabbithole http://console.neo4j.org This Graph: http://tinyurl.com/7cnvmlq 43
  • 77.
    How to useCypher in YOUR programs 44
  • 78.
    Neo4j API ExecutionEngineengine = new ExecutionEngine(graphDB); String query = „start n=node:Person(name={name}) match n-[:ACTS_IN]->movie<-[:ACTS_IN]-friend return friend“; ExecutionResult result = engine.query(query, map(„name“, „Keanu“); for (Map<String,Object> row : result) { Node friend = row.get(„friend“); } Iterator<Node> friends = result.columnAs(„friend“); http://bit.ly/cypher-queries 45
  • 79.
    How to getstarted? 46
  • 80.
    How to getstarted? ๏ Documentation 46
  • 81.
    How to getstarted? ๏ Documentation • docs.neo4j.org - tutorials+reference 46
  • 82.
    How to getstarted? ๏ Documentation • docs.neo4j.org - tutorials+reference • http://console.neo4j.org 46
  • 83.
    How to getstarted? ๏ Documentation • docs.neo4j.org - tutorials+reference • http://console.neo4j.org • Neo4j in Action 46
  • 84.
    How to getstarted? ๏ Documentation • docs.neo4j.org - tutorials+reference • http://console.neo4j.org • Neo4j in Action • Good Relationships 46
  • 85.
    How to getstarted? ๏ Documentation • docs.neo4j.org - tutorials+reference • http://console.neo4j.org • Neo4j in Action • Good Relationships ๏ Get Neo4j 46
  • 86.
    How to getstarted? ๏ Documentation • docs.neo4j.org - tutorials+reference • http://console.neo4j.org • Neo4j in Action • Good Relationships ๏ Get Neo4j • http://neo4j.org/download 46
  • 87.
    How to getstarted? ๏ Documentation • docs.neo4j.org - tutorials+reference • http://console.neo4j.org • Neo4j in Action • Good Relationships ๏ Get Neo4j • http://neo4j.org/download • http://addons.heroku.com/neo4j/ ๏ Participate • http://groups.google.com/group/neo4j • http://neo4j.meetup.com 46
  • 88.
    How to getstarted? ๏ Documentation • docs.neo4j.org - tutorials+reference • http://console.neo4j.org • Neo4j in Action • Good Relationships ๏ Get Neo4j • http://neo4j.org/download • http://addons.heroku.com/neo4j/ ๏ Participate • http://groups.google.com/group/neo4j • http://neo4j.meetup.com • a session like this one ;) 46
  • 89.
  • 90.
    Neo4j-JDBC Driver &MovieDB Dataset http://blog.neo4j.org/2012/06/wanted-your- help-in-testing-neo4j-jdbc.html 48
  • 91.
    Got a Conference?Need a Dataset? http://blog.neo4j.org/2012/08/at-conference- need-dataset-neo4j-at.html 49
  • 92.
  • 93.
    Graphs in SoftwareTechnolgoy ๏ UML Diagrams are graphs ๏ dependencies between classes, packages, modules etc are graphs ๏ Software Metrics use dependency analysis ๏ Visualizations ๏ Cyclomatic Complexity, ๏ Fan-in (afferent-coupling) / Fan-out (efferent coupling) etc. 51
  • 94.
  • 95.
    Class Diagram isa Graph 53
  • 96.
  • 97.
    But there ismore ๏Visualize & query Method, Field dependencies ๏Collaborative filtering (co-usage) ๏Ranking ๏God classes ๏Paths between classes 55
  • 98.
    Welcome to Class-Graph ๏takea JAR ๏put it under ASM ๏scan it superfast ๏pull everything into Neo4j ๏add categories, indexes ๏Have Fun http://github.com/jexp/class-graph 56
  • 99.
  • 100.
    Interactive Hands-On Session ๏Lotsof tasks ๏use Cypher to solve them http://neo4j.org/resources/cypher ๏be creative, work together ๏ask ! ๏Server http://bit.ly/innoq-neo4j ๏just the beginning 58
  • 101.
  • 102.
    Task: Find java.lang.Numberand return it START o=node:types(name="java.lang.Number")  RETURN o; 59
  • 103.
    Task: Subclasses ofNumber? •Return just the name •Order them alphabetically 60
  • 104.
    Task: Subclasses ofNumber? START n=node:types(name="java.lang.Number")  MATCH n<-[:SUPER_TYPE]-s RETURN s.name ORDER BY s.name; •Return just the name •Order them alphabetically 60
  • 105.
    Task: Which Methodsdoes it have / how many •Find the top 5 classes with the most members 61
  • 106.
    Task: Which Methodsdoes it have / how many START n=node:types(name="java.lang.Number")  MATCH n-[:METHOD_OF|FIELD_OF]->m RETURN m; •Find the top 5 classes with the most members 61
  • 107.
    Task: Calculate thefan-out of java.lang.StringBuilder •Calculate fan-in •Which class has the highest fan-out •What about package-level? 62
  • 108.
    Task: Calculate thefan-out of java.lang.StringBuilder START o=node:types(name="j.l.StringBuilder") MATCH o-[:FIELD_OF]->f-[:FIELD_TYPE]->tf, o-[:METHOD_OF]->m-[:PARAM_TYPE]->tp, m-[:RETURN_TYPE]->tr RETURN o,count(distinct tf) + count(distinct tp) + count(distinct tr) as fan_out; •Calculate fan-in •Which class has the highest fan-out •What about package-level? 62
  • 109.
    Task: Find longestInheritance Path 63
  • 110.
    Task: Find longestInheritance Path start c=node:types(name="java.lang.Object")  match path=p<-[:SUPER_TYPE*]-c  return extract(n in nodes(path) : n.name), length(path) as len order by len desc  limit 5; 63
  • 111.
    Task: Find theclass that used IOException most often 64
  • 112.
    Task: Find theclass that used IOException most often START ex=node:types(name="java.io.IOException" MATCH ex<-[:THROWS]-m<-[:METHOD_OF]-c RETURN c, count(*) ORDER BY count(*) LIMIT 5; 64
  • 113.
    Task: Which otherclasses did classes that threw IOException use most often? •What could be a source of IOExceptions 65
  • 114.
    Task: Which otherclasses did classes that threw IOException use most often? START ex=node:types(name="java.io.IOException") MATCH ex<-[:THROWS]-m<-[:METHOD_OF]-c,  mbr<-[:METHOD_OF|FIELD_OF]-c, mbr-[:FIELD_TYPE|PARAM_TYPE| RETURN_TYPE|THROWS]->other_type WHERE other_type.name =~ /.+[.].+/ RETURN other_type.name, count(*) ORDER BY count(*) desc LIMIT 10; •What could be a source of IOExceptions 65
  • 115.
    Task: Find aclass you like and add a field with your name and some type 66
  • 116.
    Task: Find aclass you like and add a field with your name and some type START c=node:types(name="void"), t=node:types(name="java.lang.reflect.Proxy")  CREATE c-[:FIELD_OF]->(field {name:“Michael“}) -[:FIELD_TYPE]->t; 66
  • 117.
    Task: Delete themost annoying class and all its methods, fields and their relationships 67
  • 118.
    Task: Delete themost annoying class and all its methods, fields and their relationships START c=node:types(name="java.awt.List"), MATCH c-[r1:FIELD_OF|METHOD_OF]->mbr-[r2]-() c-[r]-() DELETE c,mbr,r1,r2,r; 67

Editor's Notes