Peter Parada
Peter Parada

Reputation: 15

Count number of relationships in neo4j

I have 2 nodes Post and User, where user can like the post, which will create a relationship (user:User)-[:LIKES]->(post). I have a problem to calculate number of likes per post. If nobody liked it should return 0, however it always returns 0. (FYI: I am also calculating who created the post)

Here's my query:

MATCH (post:Post)
MATCH (user:User)-[:CREATED]->(post)
OPTIONAL MATCH (post)<-[likes:LIKES]-(:User)
WHERE post.uuid = {postUUID} AND NOT exists(post.deleted)
RETURN post,
       user.username AS `createdBy`,
       count(likes) AS `likes`

Thanks for help!

Upvotes: 1

Views: 924

Answers (1)

cybersam
cybersam

Reputation: 66967

This might work better for you:

MATCH (user:User)-[:CREATED]->(post:Post)
WHERE post.uuid = {postUUID} AND (NOT user.deleted OR NOT EXISTS(user.deleted))
RETURN
  post,
  user.username AS `createdBy`,
  SIZE((post)<-[:LIKES]-(:User)) AS `likes`

This query avoids the issue mentioned by @InverseFalcon by only matching Post node(s) with the specified uuid.

Also, this query will match User nodes that do have the deleted property, but with a false value. Your original query's OPTIONAL MATCH clause (which is not necessary) would only match users that did not have the deleted property at all.

Upvotes: 2

Related Questions