Marc
Marc

Reputation: 3892

How to return only the end/leaf nodes in a Neo4j cypher query?

I have a structure like so:

user-[:talking]->topic-[:categorized_in]->topic[:categorized_in]->topic... etc

Starting at a user, how would I get the furthest away topics they're talking about. Basically this represents the top level categories they are talking about. This is the only way I know to go about doing this, and it returns all of the nodes along the way, not just the leaf nodes.

START user=node(1)
MATCH user-[:talking]->x<-[:categorized_in*0..]-y
RETURN distinct y.uuid

This is my latest attempt. It seems to work, though I don't know if this is the best way to go about it?:

START user=node(1)
MATCH user-[:talking]->x<-[:categorized_in*0..]-y<-[?:pull]-z
WHERE z is null
RETURN distinct y.uuid

Upvotes: 4

Views: 1541

Answers (2)

Matt Luongo
Matt Luongo

Reputation: 14809

You can now filter against patterns in the WHERE.

So if you have a newer version of Neo4j, I think the query would look like

START user=node(1)
MATCH user-[:talking]->x<-[:categorized_in*0..]-y
WHERE NOT(y<-[:categorized_in]-())
RETURN DISTINCT y.uuid

Upvotes: 1

Marc
Marc

Reputation: 3892

So this is how to do it for anybody interested:

START user=node(1)
MATCH user-[:talking]->x<-[:categorized_in*0..]-y<-[?:categorized_in]-z
WHERE z is null
RETURN distinct y.uuid

Upvotes: 2

Related Questions