Search code examples
neo4jneo4jclient

Fetch Count of Specific Relation to a Node in Neo4j


I have a scenario in Neo4J where a "User" Node Relates to a Node "Post" with relation Name as "WRITES".Now the "Post" node can receive relation named "LIKES" from other Nodes(User).Now I want to fetch the data of the post written by the User mentioned in where Clause and it's corresponding likes count. I have written the below query but it is not working.

MATCH (user:User)-[WRITES]-(myp:Post)<-[l:LIKES]-()
where user ="xyz"
RETURN myp,count(l) as count

I intend to receive the Post which was added by the specific User and the Count of Likes and later convert it into C#. Please help.


Solution

  • The query isn't valid in a couple of ways.

    First, you're comparing a whole User node to the string "xyz" in your WHERE clause - you instead should be querying on the properties of your matched User nodes.

    Second, you're missing a colon before WRITES that means you're actually matching any relationship type and giving it the variable name WRITES in the rest of the query. You instead probably want the following:

    For example, let's say that User nodes have a 'username' property:

    MATCH (user:User)-[:WRITES]-(myp:Post)<-[l:LIKES]-()
    WHERE user.username = "xyz"
    RETURN myp, count(l) as count
    

    Also, unless the WRITES relationship is genuinely directionless (i.e. that Post nodes can somehow write Users), you should probably include an arrow in that relationship to limit the search space a bit:

    MATCH (user:User)-[:WRITES]->(myp:Post)<-[l:LIKES]-()
    WHERE user.username = "xyz"
    RETURN myp, count(l) as count
    

    If you want to return posts even if they've received no likes, we need to remove the LIKES relationship from the pattern and calculate the number of likes slightly differently:

    MATCH (user: User)-[:WRITES]->(myp:Post)
    WHERE user.username = "xyz"
    RETURN myp, size((myp)<-[:LIKES]-()) as count