This Gist is inspired by Neo4j 2.0 is coming blog post by Max De Marzi
Let’s use a sample dataset related to the Movie Industry (Movies, Actors, Directors, etc.) that looks like:
CREATE (TheMatrix {title:'The Matrix', released:1999, tagline:'Welcome to the Real World'})
CREATE (Keanu {name:'Keanu Reeves', born:1964})
CREATE (Carrie {name:'Carrie-Anne Moss', born:1967})
CREATE (Laurence {name:'Laurence Fishburne', born:1961})
CREATE (Hugo {name:'Hugo Weaving', born:1960})
CREATE (AndyW {name:'Andy Wachowski', born:1967})
CREATE (LanaW {name:'Lana Wachowski', born:1965})
CREATE (JoelS {name:'Joel Silver', born:1952})
CREATE
(Keanu)-[:ACTED_IN {roles:['Neo']}]->(TheMatrix),
(Carrie)-[:ACTED_IN {roles:['Trinity']}]->(TheMatrix),
(Laurence)-[:ACTED_IN {roles:['Morpheus']}]->(TheMatrix),
(Hugo)-[:ACTED_IN {roles:['Agent Smith']}]->(TheMatrix),
(AndyW)-[:DIRECTED]->(TheMatrix),
(LanaW)-[:DIRECTED]->(TheMatrix),
(JoelS)-[:PRODUCED]->(TheMatrix)And is fully compatible with Neo4j 1.9 (without manual indexes, Cypher is not supporting these).
Then we’ll MATCH the nodes in the graph that should have those labels, and set them. For example, every node that has a “title” property is a Movie, and every node that has an outgoing “ACTED_IN” relationship is an Actor.
MATCH node
WHERE has(node.title)
SET node:MovieMATCH node
WHERE (node)-[:ACTED_IN]->()
SET node:ActorMATCH node
WHERE (node)-[:DIRECTED]->()
SET node:DirectorMATCH node
WHERE (node)-[:WROTE]->()
SET node:WriterMATCH node
WHERE (node)-[:PRODUCED]->()
SET node:ProducerMATCH node
WHERE (node)-[:FOLLOWS]-()
SET node:UserThis data is how you’d create data normally in Neo4j 1.9. To update it to 2.0 and make use of Labels and Indexes, we just need to update it slightly. Looking at our graph, we can see we have nodes that represent Actors, Directors, Movies, Writers, etc. Each one of these also has a primary way of being found in the graph, names for various types of people, and titles for Movies. So we’ll create Indexes on these properties for their individual Labels:
CREATE INDEX ON :Actor(name)CREATE INDEX ON :Director(name)CREATE INDEX ON :Writer(name)CREATE INDEX ON :Producer(name)CREATE INDEX ON :Movie(title)CREATE INDEX ON :User(name)Now, we can finally ask a Query using Neoj4 2.0 Labels and indexes:
MATCH (a:Actor) -[r:ACTED_IN]->(m:Movie)
RETURN a.name, r.roles, m.titleMATCH a:Actor
WHERE a.name =~ '^[KH].*'
RETURN a.nameYeah, it’s really that easy. Some folks have asked for a “Migration Tool”, but the reality is that a little Cypher does all the work for us.