Neo4j 2: Learning CypherJUG Marche - June 2014
Onofrio Panzarino
Graph databases and me
● RDF (Semantic web)○ 2004-2005: Sesame (SPARQL)
● Neo4j○ 2011: Java API (Embedded), Traversers○ 2013: Cypher
Twitter: @onof80 Blog: http://learningcypher.blogspot.com My book: Learning Cypher
What is Neo4j
- Graph database- ACID transaction- 2 running modes > Embedded (JAVA API) > Server (REST)- Cypher Query Language
Model: nodes and relationships
Source: http://gist.neo4j.org/?8635758
Schema?
Schemaless (key-value)
Nodes: > propertiesRelationships: > properties
SchemaNodes:
0+ LabelsRelationships: 1 TypeIndexes+Constraints
Querying: REST API
Properties of node with id 32:GET http://localhost:7474/db/data/node/32/properties
{
"user": "@onof80",
"lastLogin": 1394304000,
"tags": ["Java","Scala","NoSql"]
}
Traversing the graphfor ( Path position : db.traversalDescription()
.depthFirst()
.relationships( Rels.KNOWS, Direction.INCOMING )
.evaluator( Evaluators.toDepth( 5 ) )
.traverse( node6 ) )
{
output += position + "\n";
}
(6)
(6)<--[KNOWS,1]--(3)
(6)<--[KNOWS,1]--(3)<--[KNOWS,6]--(0)
(6)<--[KNOWS,1]--(3)<--[KNOWS,6]--(0)<--[KNOWS,4]--(5)
Powerful but hardcoded
Querying with Cypher
START n=node(10)MATCH path =(n)<-[:KNOWS*0..5]-()RETURN path
http://console.neo4j.org/
Create a full path
CREATE (a:Language { name: "Java"}),
(b:Language { name: "Scala" }),
(c:Language { name: "JavaScript" }),
(jvm:Platfom { name: "JVM" }),
path=(a)-[r:RUNS_ON]->(jvm)
<-[r2:RUNS_ON]-(b)
RETURN path
MERGE
Look for a pattern:● Found? Match it● Else create it
MERGE (a:Language { name: "Java" })
SET a.version = 8
RETURN a
Idempotent operations
MATCH (a:Language)REMOVE a.version
MATCH (a:Language)DELETE a
But...
MERGE (a:Language { name: "Java" })
ON MATCH SET a.version = a.version + 1
ON CREATE SET a.version = 1
RETURN a
Optional paths
MATCH (a:Language)OPTIONAL MATCH (a)-[:RUNS_ON]-(b)RETURN a,bORDER BY a.name
Aggregations
MATCH (a:Language)OPTIONALMATCH (a)-[:RUNS_ON]-(b)RETURN b.name, COUNT(*)
Other keywords
Splitting queriesWITH
Manipulating collectionsEXTRACT, FILTER, REDUCE
PredicatesALL, ANY, SINGLE, NONE
More features
IntegrationLOAD CSV WITH HEADERS
FROM <file> AS line
CREATE ...
ProfilingPROFILE <query>
Any questions?
Q&A
More infos:http://docs.neo4j.org/ My bookAll Neo4j books