dimecres, 8 de gener del 2014

More on Neo4J 2.x: Querying over labels


I'm just starting with Neo4J and got straight into v2.0 so my first models already use labels. I just got into a case where I expected labels be of help but not sure if what I want to do is possible. Let me explain:

THE DOMAIN

Let's imagine we modelled a food chain: (in pseudo-cypher)

   (grass:Vegetable)-[:EATS]-(marie:Cow)
   (marie)-[:EATS]-(ferocious:Velociraptor)
   (marie)-[:EATS]-(joseph:Human)


In this example, 'josep' and 'ferocious' shared a great meal of 'marie'. Meanwhile poor Marie the Cow had had a last meal of grass.

DETECTING CANNIBALISM

Now, Imagine I wanted to locate cannibalism relations in my graph. It's ok for any species to eat other species but it's unacceptable to eat those of your same species. So I want to locate nodes labelled X eating other nodes also labelled X. Put another way, I'd like to write predicates over the label. So far the only option I found was replicating the label information into a property.

Turns out the solution was right in my face... that is, in the docs.

   MATCH (n)--(p)
     WHERE labels(n) = labels(p)
     RETURN n, p


Now, this works because I only added a label to each of my nodes but if I were to use labels aggressively this query would not solve my cannibalism detection.