SlideShare a Scribd company logo
Name Surname
email@domain.com
Presentation TitleLeague of
Graphs
Dmitry Vrublevsky
@Me
Software engineer @
ƀ dmitry@vrublevsky.me
@FylmTM
į vrublevsky.me
Neueda4j / awesome-neo4j
{75 } A curated list of Neo4j resources.
Neueda4j / jetbrains-plugin-cypher
{24 } Cypher plugin for Jetbrains IDE’s.
? / ?
{? } Next awesome project!
Agenda
1. League of Legends
2. Neo4j
3. Data import
4. Queries
Winner?
League of Legends
“Poros are the mysterious, magical and most-loved
inhabitants originating from the Howling Abyss.”
League of Legends
is multiplayer online battle arena,
real-time strategy video game
developed and published by
Riot Games
Me
Unranked Bronze Silver Gold
Platinum Diamond Master Challenger
League of Legends?
1. I play this game a lot
2. Rich API
3. There is library for API
https://developer.riotgames.com
meraki-analytics/Orianna
A Java adaptation of the Riot Games LoL API
Summoner summoner =
RiotAPI.getSummonerByName(“FylmTM");


println(summoner.getName()
+ " is a level “ + summoner.getLevel());
Neo4j
Highly scalable native graph
database that leverages data
relationships as 

first-class entities.
by Neo Technology, Inc.
http://db-engines.com/en/ranking
GRAPH
NOT GRAPH
Features
Native Processing &
Storage
ACID
Cypher - Graph Query
Language
REST & Native API
Lock Manager
High-performance cache
Clustering
Backups
Monitoring
Community Enterprise
First-class
details: ♥:LIKES
:DMITRY
:JUG
works_with: Neo4j
day: 28.05.2016
Properties
Labels
Type
Native
1. “Native” storage
2. “Native” processing
“Native” storage
Specifically designed to
store and manage graphs.
http://neo4j.com/developer/graph-db-vs-rdbms/
http://neo4j.com/developer/graph-db-vs-rdbms/
http://neo4j.com/developer/graph-db-vs-rdbms/
“Native” processing
Efficient way of processing
graph data since connected
nodes physically “point” to
each other
a.k.a. “index-free adjacency”
Storage layout
Node (15 bytes)
in_use
next_rel_id
next_prop_id
labels
extra
Relationship (34 bytes)
directed | in_use
first_node
second_node
rel_type
first_prev_rel_id
first_next_rel_id
second_prev_rel_id
second_next_rel_id
next_prop_id
first_in_chain_markers
Storage math
Node_Offset = Node_Size * Node_ID
Rel_Offset = Rel_Size * Rel_ID
Traversal (Node -> Relationship)
{5} Node (15 bytes)
next_rel_id {2}
{<int>} - entity id
<int>B - offset
Relationships (34 bytes)
{0}
2 * 34 = 68
0B
{1}34B
{2}68B
{3}102B
{4}136B
{5}170B
Traversal (Relationship -> Node)
{2} Relationship (34 bytes)
{<int>} - entity id
<int>B - offset
Nodes (15 bytes)
{0}0B
{1}15B
{2}30B
{3}45B
{4}60B
{5}75B
first_node {1}
second_node {4}
“Native” summary
O(1) traversal hops
Avoid super nodes!
Cypher
Cypher is a declarative
graph query language that
allows for expressive and
efficient querying.
https://github.com/opencypher/openCypher
Cypher
( ) - node
--> - relationship
Keywords:
- MATCH
- CREATE
- WHERE
- RETURN
MATCH (jug) RETURN jug
MATCH (attendees)-->(jug) 

RETURN *
MATCH (attendees)-->(jug)
WHERE jug.city = “Kaunas”

RETURN *
Cypher
MATCH (you:Person {name: "Dmitry"})
CREATE (you)-[like:LIKE]->(neo:Database {name: "Neo4j"})
RETURN you, like, neo
Whiteboard friendly
data modelling
CREATE (alice:Person {name: "Alice"})

CREATE (bob:Person {name: "Bob"})

CREATE (carol:Person {name: "Carol"})

CREATE (iphone:Device {name: "iPhone"})



CREATE (alice)-[:HAS]->(iphone)

CREATE (bob)-[:WANTS]->(iphone)



CREATE (alice)<-[:FOLLOWS]-(bob)

CREATE (alice)-[:FOLLOWS]->(bob)

CREATE (carol)-[:FOLLOWS]->(bob)



CREATE (bob)<-[:AUTHOR]-(:Comment {text: "Thoughts?"})

<-[:COMMENT]-(iphone)

CREATE (carol)<-[:AUTHOR]-(:Comment {text: "<3 it"})

<-[:COMMENT]-(iphone)
Data import
1. Retrieve data using Orianna
2. Load data as-is in Neo4j
Dependencies
dependencies {

compile 'com.robrua:orianna:2.4.3-SNAPSHOT'

compile 'org.neo4j:neo4j:2.3.3'

}
Create database
File dbDir = new File(databasePath);


GraphDatabaseService db = new GraphDatabaseFactory()

.newEmbeddedDatabaseBuilder(dbDir)

.newGraphDatabase();
Transaction
try (Transaction tx = db.beginTx()) { 

// Do cool stuff


tx.success();

}
Load data
Summoner summoner =
RiotAPI.getSummonerByName(“FylmTM");
Node node = db.createNode();

node.addLabel(Labels.Summoner);

node.setProperty(KEY_ID, summoner.getID());

node.setProperty(KEY_NAME, summoner.getName());

node.setProperty(KEY_LEVEL, summoner.getLevel());
In the end
neo4j-contrib/neo4j-apoc-procedures
Awesome procedures for Neo4j 3.0 - codenamed "apoc"
// examines the full graph to create the meta-graph

CALL apoc.meta.graph();
Apoc was the technician and driver on board of the
Nebuchadnezzar in the Matrix movie.
He was killed by Cypher.
Import result
• Season 6, EUNE region
• Players: me & 7 friends
MATCH (n) RETURN count(n) as nodeCount
nodeCount
336729
Queries
Query #1 How many games I have played?
MATCH (s:Summoner {name: "FylmTM"})

MATCH (s)-[:PARTICIPATED|:PARTICIPATED_IN_MATCH]->(sMatch)

RETURN count(sMatch); // 59 ms
Count
110
Query #2 Who are my friends?
MATCH (s:Summoner {name: "FylmTM"})

MATCH (s)-[:PARTICIPATED]-()-[:PARTICIPATED_IN_MATCH]

->(sMatch)<-

[:PARTICIPATED_IN_MATCH]-()-[:PARTICIPATED]-(f)

WITH f.name as friendName, count(f) as gamesTogether

WHERE gamesTogether > 2

RETURN friendName, gamesTogether

ORDER BY gamesTogether DESC // 55 ms
friendName gamesTogether
Cryptael 107
Henua 28
Iger 11
XXpoMMou 10
yesCold 8
eskiuzi 3
Query #3 Most dangerous champions?
name total won lost %
Alistar 7 1 6 86%
Jax 12 3 9 75%
LeBlanc 8 2 6 75%
Dr. Mundo 7 2 5 71%
Miss Fortune 10 3 7 70%
MATCH (s:Summoner {name: "FylmTM"})

MATCH (s)-[:PARTICIPATED]->()-[:PLAYED_FOR_TEAM]->

(team {winner: true})<-[:HAS_TEAM]-()-[:HAS_TEAM]->(o)

<-[:PLAYED_FOR_TEAM]-()-[:PARTICIPATED_WITH_CHAMPION]->(c)

RETURN c.name as championName, count(c) as winCount

ORDER BY winCount DESC
Alistar Jax
Query #4 Any statistics?
MATCH (s:Summoner) WHERE s.name IN ["MrMgr", "Cryptael"]

MATCH (s)-[:PARTICIPATED|:PARTICIPANT_TIMELINE*2]->(pt)-[r]->(ptd)

WHERE pt.role = "SOLO" AND pt.lane = "MIDDLE"

AND r.name IN ["getCreepsPerMinDeltas", "getGoldPerMinDeltas"]

WITH s.name as name, r.name as stat,

sum(ptd.zero_to_ten) as `sum_0-10`,

size(filter(x IN collect(ptd.zero_to_ten) WHERE x <> 0))

as `size_0-10`,

sum(ptd.ten_to_twenty) as `sum_10-20`,

size(filter(x IN collect(ptd.ten_to_twenty) WHERE x <> 0))

as `size_10-20`,

sum(ptd.twenty_to_thirty) as `sum_20-30`,

size(filter(x IN collect(ptd.twenty_to_thirty) WHERE x <> 0))

as `size_20-30`,

sum(ptd.thirty_to_end) as `sum_30+`,

size(filter(x IN collect(ptd.thirty_to_end) WHERE x <> 0))

as `size_30+`

RETURN name, stat,

`sum_0-10` / `size_0-10` as `0-10`,

`sum_10-20` / `size_10-20` as `10-20`,

`sum_20-30` / `size_20-30` as `20-30`,

`sum_30+` / `size_30+` as `30+`

ORDER BY name, stat
creeps/min
0
2
4
6
8
0-10 10-20 20-30 30+
Cryptael
MrMgr
gold/min
0
150
300
450
600
0-10 10-20 20-30 30+
Cryptael
MrMgr
Cryptael
MrMgr (#27 in EUNE)
Takeaways
• Neo4j is easy to use
• Build schema on the fly
• Cypher is a handy tool for exploration
• Find value in your data
League of Graphs

More Related Content

What's hot

Plano de ação + educação
Plano de ação + educaçãoPlano de ação + educação
Plano de ação + educação
Jackson Jara
 
Relatório pedagógico e avaliação descritiva
Relatório pedagógico e avaliação descritivaRelatório pedagógico e avaliação descritiva
Relatório pedagógico e avaliação descritiva
Andreia Carla Lobo
 
Discutindo diagnósticos de escrita (SLIDES 3ª Formação NUALFA)
Discutindo diagnósticos de escrita (SLIDES 3ª Formação NUALFA)Discutindo diagnósticos de escrita (SLIDES 3ª Formação NUALFA)
Discutindo diagnósticos de escrita (SLIDES 3ª Formação NUALFA)
Edeil Reis do Espírito Santo
 
Projeto Minha Cidade
Projeto Minha CidadeProjeto Minha Cidade
Projeto Minha Cidade
Paula Pereira
 
Projeto político pedagógico
Projeto político pedagógicoProjeto político pedagógico
Projeto político pedagógico
mauriliojr
 
Modelo memorando apresentação
Modelo memorando apresentaçãoModelo memorando apresentação
Modelo memorando apresentação
Mauricio Moraes
 
04 e 05 secretariado (tipos de carta comercial)
04 e 05  secretariado (tipos de carta comercial)04 e 05  secretariado (tipos de carta comercial)
04 e 05 secretariado (tipos de carta comercial)
Elizeu Ferro
 

What's hot (20)

Plano de ação + educação
Plano de ação + educaçãoPlano de ação + educação
Plano de ação + educação
 
Modelo do dossiê 2013
Modelo do dossiê 2013Modelo do dossiê 2013
Modelo do dossiê 2013
 
Relatório pedagógico e avaliação descritiva
Relatório pedagógico e avaliação descritivaRelatório pedagógico e avaliação descritiva
Relatório pedagógico e avaliação descritiva
 
Discutindo diagnósticos de escrita (SLIDES 3ª Formação NUALFA)
Discutindo diagnósticos de escrita (SLIDES 3ª Formação NUALFA)Discutindo diagnósticos de escrita (SLIDES 3ª Formação NUALFA)
Discutindo diagnósticos de escrita (SLIDES 3ª Formação NUALFA)
 
Memorando interno
Memorando interno Memorando interno
Memorando interno
 
Modelo de ata
Modelo de ataModelo de ata
Modelo de ata
 
Projeto Minha Cidade
Projeto Minha CidadeProjeto Minha Cidade
Projeto Minha Cidade
 
Exemplo resolvido modelo peps
Exemplo resolvido modelo pepsExemplo resolvido modelo peps
Exemplo resolvido modelo peps
 
Projeto político pedagógico
Projeto político pedagógicoProjeto político pedagógico
Projeto político pedagógico
 
Modelo memorando apresentação
Modelo memorando apresentaçãoModelo memorando apresentação
Modelo memorando apresentação
 
ALFABETIZAÇÃO
ALFABETIZAÇÃOALFABETIZAÇÃO
ALFABETIZAÇÃO
 
Plano de Marketing e Comunição ESAMC - Uberlândia Esporte Clube
Plano de Marketing e Comunição ESAMC - Uberlândia Esporte ClubePlano de Marketing e Comunição ESAMC - Uberlândia Esporte Clube
Plano de Marketing e Comunição ESAMC - Uberlândia Esporte Clube
 
04 e 05 secretariado (tipos de carta comercial)
04 e 05  secretariado (tipos de carta comercial)04 e 05  secretariado (tipos de carta comercial)
04 e 05 secretariado (tipos de carta comercial)
 
PROJETO FESTIVAL DE TALENTOS "ARTISTAS MARANHENSES"
PROJETO FESTIVAL DE TALENTOS "ARTISTAS MARANHENSES"PROJETO FESTIVAL DE TALENTOS "ARTISTAS MARANHENSES"
PROJETO FESTIVAL DE TALENTOS "ARTISTAS MARANHENSES"
 
Modelos de curriculo
Modelos de curriculoModelos de curriculo
Modelos de curriculo
 
Aula de Contabilidade Basica.ppt
Aula de Contabilidade Basica.pptAula de Contabilidade Basica.ppt
Aula de Contabilidade Basica.ppt
 
Carta de apresentação
Carta de apresentaçãoCarta de apresentação
Carta de apresentação
 
Ambev - O guia completo com informações sobre a empresa
Ambev - O guia completo com informações sobre a empresaAmbev - O guia completo com informações sobre a empresa
Ambev - O guia completo com informações sobre a empresa
 
Planejando a abertura da sua empresa
Planejando a abertura da sua empresaPlanejando a abertura da sua empresa
Planejando a abertura da sua empresa
 
Estabelecimento de política e risco de crédito
Estabelecimento de política e risco de créditoEstabelecimento de política e risco de crédito
Estabelecimento de política e risco de crédito
 

Similar to League of Graphs

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
PyCon2009_AI_Alt
PyCon2009_AI_AltPyCon2009_AI_Alt
PyCon2009_AI_Alt
Hiroshi Ono
 
Code as data as code.
Code as data as code.Code as data as code.
Code as data as code.
Mike Fogus
 

Similar to League of Graphs (20)

Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
The Curious Clojurist - Neal Ford (Thoughtworks)
The Curious Clojurist - Neal Ford (Thoughtworks)The Curious Clojurist - Neal Ford (Thoughtworks)
The Curious Clojurist - Neal Ford (Thoughtworks)
 
Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...
Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...
Atmosphere 2016 - Krzysztof Kaczmarek - Don't fear the brackets - Clojure in ...
 
Как мы сделали многопользовательскую браузерную игру для HL++ с воксельной гр...
Как мы сделали многопользовательскую браузерную игру для HL++ с воксельной гр...Как мы сделали многопользовательскую браузерную игру для HL++ с воксельной гр...
Как мы сделали многопользовательскую браузерную игру для HL++ с воксельной гр...
 
Playing CTFs for Fun & Profit
Playing CTFs for Fun & ProfitPlaying CTFs for Fun & Profit
Playing CTFs for Fun & Profit
 
Mongo db mug_2012-02-07
Mongo db mug_2012-02-07Mongo db mug_2012-02-07
Mongo db mug_2012-02-07
 
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
Самые вкусные баги из игрового кода: как ошибаются наши коллеги-программисты ...
 
Recognize Godzilla
Recognize GodzillaRecognize Godzilla
Recognize Godzilla
 
PyCon2009_AI_Alt
PyCon2009_AI_AltPyCon2009_AI_Alt
PyCon2009_AI_Alt
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Tips and Tricks for Avoiding Common Query Pitfalls Christian Kurze
Tips and Tricks for Avoiding Common Query Pitfalls Christian KurzeTips and Tricks for Avoiding Common Query Pitfalls Christian Kurze
Tips and Tricks for Avoiding Common Query Pitfalls Christian Kurze
 
Tokyo APAC Groundbreakers tour - The Complete Java Developer
Tokyo APAC Groundbreakers tour - The Complete Java DeveloperTokyo APAC Groundbreakers tour - The Complete Java Developer
Tokyo APAC Groundbreakers tour - The Complete Java Developer
 
Ruby on Rails: Tasty Burgers
Ruby on Rails: Tasty BurgersRuby on Rails: Tasty Burgers
Ruby on Rails: Tasty Burgers
 
MongoDB.local Austin 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local Austin 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB.local Austin 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local Austin 2018: Tips and Tricks for Avoiding Common Query Pitfalls
 
Tips and Tricks for Avoiding Common Query Pitfalls
Tips and Tricks for Avoiding Common Query PitfallsTips and Tricks for Avoiding Common Query Pitfalls
Tips and Tricks for Avoiding Common Query Pitfalls
 
Code as data as code.
Code as data as code.Code as data as code.
Code as data as code.
 
[EN] Ada Lovelace Day 2014 - Tampon run
[EN] Ada Lovelace Day 2014  - Tampon run[EN] Ada Lovelace Day 2014  - Tampon run
[EN] Ada Lovelace Day 2014 - Tampon run
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processingpa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processing
 
Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)
 
PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)
 

Recently uploaded

AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
Alluxio, Inc.
 

Recently uploaded (20)

Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting software
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 

League of Graphs

  • 2. Dmitry Vrublevsky @Me Software engineer @ ƀ dmitry@vrublevsky.me @FylmTM į vrublevsky.me
  • 3.
  • 4.
  • 5. Neueda4j / awesome-neo4j {75 } A curated list of Neo4j resources. Neueda4j / jetbrains-plugin-cypher {24 } Cypher plugin for Jetbrains IDE’s. ? / ? {? } Next awesome project!
  • 6. Agenda 1. League of Legends 2. Neo4j 3. Data import 4. Queries
  • 7.
  • 8. Winner? League of Legends “Poros are the mysterious, magical and most-loved inhabitants originating from the Howling Abyss.”
  • 9. League of Legends is multiplayer online battle arena, real-time strategy video game developed and published by Riot Games
  • 10.
  • 11. Me Unranked Bronze Silver Gold Platinum Diamond Master Challenger
  • 12.
  • 13. League of Legends? 1. I play this game a lot 2. Rich API 3. There is library for API https://developer.riotgames.com
  • 14.
  • 15. meraki-analytics/Orianna A Java adaptation of the Riot Games LoL API Summoner summoner = RiotAPI.getSummonerByName(“FylmTM"); 
 println(summoner.getName() + " is a level “ + summoner.getLevel());
  • 16. Neo4j Highly scalable native graph database that leverages data relationships as 
 first-class entities. by Neo Technology, Inc.
  • 18. GRAPH
  • 20. Features Native Processing & Storage ACID Cypher - Graph Query Language REST & Native API Lock Manager High-performance cache Clustering Backups Monitoring Community Enterprise
  • 22. Native 1. “Native” storage 2. “Native” processing
  • 23. “Native” storage Specifically designed to store and manage graphs.
  • 27. “Native” processing Efficient way of processing graph data since connected nodes physically “point” to each other a.k.a. “index-free adjacency”
  • 28. Storage layout Node (15 bytes) in_use next_rel_id next_prop_id labels extra Relationship (34 bytes) directed | in_use first_node second_node rel_type first_prev_rel_id first_next_rel_id second_prev_rel_id second_next_rel_id next_prop_id first_in_chain_markers
  • 29. Storage math Node_Offset = Node_Size * Node_ID Rel_Offset = Rel_Size * Rel_ID
  • 30. Traversal (Node -> Relationship) {5} Node (15 bytes) next_rel_id {2} {<int>} - entity id <int>B - offset Relationships (34 bytes) {0} 2 * 34 = 68 0B {1}34B {2}68B {3}102B {4}136B {5}170B
  • 31. Traversal (Relationship -> Node) {2} Relationship (34 bytes) {<int>} - entity id <int>B - offset Nodes (15 bytes) {0}0B {1}15B {2}30B {3}45B {4}60B {5}75B first_node {1} second_node {4}
  • 32. “Native” summary O(1) traversal hops Avoid super nodes!
  • 33. Cypher Cypher is a declarative graph query language that allows for expressive and efficient querying. https://github.com/opencypher/openCypher
  • 34. Cypher ( ) - node --> - relationship Keywords: - MATCH - CREATE - WHERE - RETURN MATCH (jug) RETURN jug MATCH (attendees)-->(jug) 
 RETURN * MATCH (attendees)-->(jug) WHERE jug.city = “Kaunas”
 RETURN *
  • 35. Cypher MATCH (you:Person {name: "Dmitry"}) CREATE (you)-[like:LIKE]->(neo:Database {name: "Neo4j"}) RETURN you, like, neo
  • 37.
  • 38.
  • 39. CREATE (alice:Person {name: "Alice"})
 CREATE (bob:Person {name: "Bob"})
 CREATE (carol:Person {name: "Carol"})
 CREATE (iphone:Device {name: "iPhone"})
 
 CREATE (alice)-[:HAS]->(iphone)
 CREATE (bob)-[:WANTS]->(iphone)
 
 CREATE (alice)<-[:FOLLOWS]-(bob)
 CREATE (alice)-[:FOLLOWS]->(bob)
 CREATE (carol)-[:FOLLOWS]->(bob)
 
 CREATE (bob)<-[:AUTHOR]-(:Comment {text: "Thoughts?"})
 <-[:COMMENT]-(iphone)
 CREATE (carol)<-[:AUTHOR]-(:Comment {text: "<3 it"})
 <-[:COMMENT]-(iphone)
  • 40. Data import 1. Retrieve data using Orianna 2. Load data as-is in Neo4j
  • 42. Create database File dbDir = new File(databasePath); 
 GraphDatabaseService db = new GraphDatabaseFactory()
 .newEmbeddedDatabaseBuilder(dbDir)
 .newGraphDatabase();
  • 43. Transaction try (Transaction tx = db.beginTx()) { 
 // Do cool stuff 
 tx.success();
 }
  • 44. Load data Summoner summoner = RiotAPI.getSummonerByName(“FylmTM"); Node node = db.createNode();
 node.addLabel(Labels.Summoner);
 node.setProperty(KEY_ID, summoner.getID());
 node.setProperty(KEY_NAME, summoner.getName());
 node.setProperty(KEY_LEVEL, summoner.getLevel());
  • 46.
  • 47. neo4j-contrib/neo4j-apoc-procedures Awesome procedures for Neo4j 3.0 - codenamed "apoc" // examines the full graph to create the meta-graph
 CALL apoc.meta.graph(); Apoc was the technician and driver on board of the Nebuchadnezzar in the Matrix movie. He was killed by Cypher.
  • 48. Import result • Season 6, EUNE region • Players: me & 7 friends MATCH (n) RETURN count(n) as nodeCount nodeCount 336729
  • 50. Query #1 How many games I have played? MATCH (s:Summoner {name: "FylmTM"})
 MATCH (s)-[:PARTICIPATED|:PARTICIPATED_IN_MATCH]->(sMatch)
 RETURN count(sMatch); // 59 ms Count 110
  • 51. Query #2 Who are my friends? MATCH (s:Summoner {name: "FylmTM"})
 MATCH (s)-[:PARTICIPATED]-()-[:PARTICIPATED_IN_MATCH]
 ->(sMatch)<-
 [:PARTICIPATED_IN_MATCH]-()-[:PARTICIPATED]-(f)
 WITH f.name as friendName, count(f) as gamesTogether
 WHERE gamesTogether > 2
 RETURN friendName, gamesTogether
 ORDER BY gamesTogether DESC // 55 ms friendName gamesTogether Cryptael 107 Henua 28 Iger 11 XXpoMMou 10 yesCold 8 eskiuzi 3
  • 52. Query #3 Most dangerous champions? name total won lost % Alistar 7 1 6 86% Jax 12 3 9 75% LeBlanc 8 2 6 75% Dr. Mundo 7 2 5 71% Miss Fortune 10 3 7 70% MATCH (s:Summoner {name: "FylmTM"})
 MATCH (s)-[:PARTICIPATED]->()-[:PLAYED_FOR_TEAM]->
 (team {winner: true})<-[:HAS_TEAM]-()-[:HAS_TEAM]->(o)
 <-[:PLAYED_FOR_TEAM]-()-[:PARTICIPATED_WITH_CHAMPION]->(c)
 RETURN c.name as championName, count(c) as winCount
 ORDER BY winCount DESC
  • 54.
  • 55. Query #4 Any statistics? MATCH (s:Summoner) WHERE s.name IN ["MrMgr", "Cryptael"]
 MATCH (s)-[:PARTICIPATED|:PARTICIPANT_TIMELINE*2]->(pt)-[r]->(ptd)
 WHERE pt.role = "SOLO" AND pt.lane = "MIDDLE"
 AND r.name IN ["getCreepsPerMinDeltas", "getGoldPerMinDeltas"]
 WITH s.name as name, r.name as stat,
 sum(ptd.zero_to_ten) as `sum_0-10`,
 size(filter(x IN collect(ptd.zero_to_ten) WHERE x <> 0))
 as `size_0-10`,
 sum(ptd.ten_to_twenty) as `sum_10-20`,
 size(filter(x IN collect(ptd.ten_to_twenty) WHERE x <> 0))
 as `size_10-20`,
 sum(ptd.twenty_to_thirty) as `sum_20-30`,
 size(filter(x IN collect(ptd.twenty_to_thirty) WHERE x <> 0))
 as `size_20-30`,
 sum(ptd.thirty_to_end) as `sum_30+`,
 size(filter(x IN collect(ptd.thirty_to_end) WHERE x <> 0))
 as `size_30+`
 RETURN name, stat,
 `sum_0-10` / `size_0-10` as `0-10`,
 `sum_10-20` / `size_10-20` as `10-20`,
 `sum_20-30` / `size_20-30` as `20-30`,
 `sum_30+` / `size_30+` as `30+`
 ORDER BY name, stat
  • 56. creeps/min 0 2 4 6 8 0-10 10-20 20-30 30+ Cryptael MrMgr gold/min 0 150 300 450 600 0-10 10-20 20-30 30+ Cryptael MrMgr Cryptael MrMgr (#27 in EUNE)
  • 57. Takeaways • Neo4j is easy to use • Build schema on the fly • Cypher is a handy tool for exploration • Find value in your data