4

With the introduction of labels, neo4j got a neat mechanisms for managing entities. Now, let's assume for a moment that we have a generic graph with lots of different entities and would like to find out what kind of entities (labels) relate to each other. Here's a starting point: http://console-test.neo4j.org/?id=wdnbuj

Graph Setup:
CYPHER 2.0
create 
(_1:Crew  {name:"Neo"}),
(_2:Crew  {name:"Morpheus"}),
(_3:Crew  {name:"Trinity"}),
(_4:Language  {name:"Cypher"}),
(_5:Machines  {name:"Agent Smith"}),
(_6:Machines  {name:"The Architect"}),
_1-[:KNOWS]->_2,
_1-[:LOVES]->_3,
_2-[:KNOWS]->_3,
_2-[:KNOWS]->_4,
_4-[:KNOWS]->_5,
_5-[:CODED_BY]->_6

Query:
CYPHER 2.0 
match x-[r]->y 
return head(labels(x)) as head, type(r), head(labels(y)) as tail

That would get us an overview of entities that relate to each other:

+--------------------------------------+
| head       | type(r)    | tail       |
+--------------------------------------+
| "Machines" | "CODED_BY" | "Machines" |
| "Language" | "KNOWS"    | "Machines" |
| "Crew"     | "KNOWS"    | "Crew"     |
| "Crew"     | "KNOWS"    | "Language" |
| "Crew"     | "KNOWS"    | "Crew"     |
| "Crew"     | "LOVES"    | "Crew"     |
+--------------------------------------+

Now. Is there any Cypher query which would return us distinct values for these triples?

Bonus question: can we get the counts/frequencies of them?

Michael
  • 695
  • 2
  • 12
  • 36

1 Answers1

2

I just used your starting query, adding distinct and count. Is that what you were looking for? Or did you want me to break out the labels from the label collection (which isn't easy without an unwind function of some sort).

match x-[r]->y 
return distinct head(labels(x)) as head, type(r), head(labels(y)) as tail

match x-[r]->y 
return head(labels(x)) as head, type(r), head(labels(y)) as tail, count(*)
Eve Freeman
  • 32,467
  • 4
  • 86
  • 101
  • Grats. You just made me feel dumb as a shoe. – Michael May 17 '13 at 12:04
  • Lol. Getting all of the labels... now that's another story. – Eve Freeman May 17 '13 at 12:09
  • Well, there's a pull request on that: https://github.com/neo4j/neo4j/pull/742 For now, you can just fetch a list of all distinct label combinations and process that with whatever language you're using... – Michael May 17 '13 at 14:09