cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

How can I check for multiple relationships and return distinct values on select node types?

geronimo4j
Graph Buddy

I have a graph that has Users who can have Posts that can tag Tags and also have Ratings.

I'm trying to return all posts that have ratings where both "Post" and the "Tags" are distinct.

So I tried something (and many variations of) this:

MATCH (this)-[:WROTE]->(post:Post)-[:HAS_RATING]->(rating:Rating)
MATCH (post)-[:TAGGED]-(t:Tag)
WITH DISTINCT t, post
RETURN DISTINCT post,
ORDER BY post.date DESC

But it's not working. Essentially I'll get responses where you'll find different posts that each tag the same Tag.

So now I'm trying to figure out how to return distinct posts where across all posts no single Tag is every returned twice.

Would anybody have any thoughts on this one? Would be greatly appreciated!

1 REPLY 1

First, DISTINCT is a keyword that operates across the entire row, not just for a single variable. So WITH DISTINCT t, post means that the combination of t and post is distinct (no two rows will have the same t AND post values).

If you want to find :Tags that only tag a single post, and that each of those single posts only have that single tag, then you can use this:

MATCH (t:Tag)
WHERE size((t)-[:TAGGED]->()) = 1
MATCH (t)-[:TAGGED]->(post:Post)
WHERE size(()-[:TAGGED]->(post)) = 1 AND (post)-[:HAS_RATING]->()
RETURN post
ORDER BY post.date DESC