Count distinct values in the neighborhood

Hello,

I'm having some issues with a Cypher query that throws an error. Basically for each node, I would like to look at the neighbors and count how many of them have a property with a certain categorical value. Then, I would like to edit the starting node with new properties counting the number of neighbors that fall within each category.

For example, for property "ACTIVITY":

  • 2 neighbors have value "Activity_Value1"
  • 1 neighbor has value "Activity_Value2"
    ...
  • X neighbors have value "Activity_ValueN"

So I would like to set properties like:

  • Credit_Activity_Value1 : 2
  • Credit_Activity_Value2 : 1
    ...
  • Credit_Activity_ValueN: XX

Here is my Cypher query :


MATCH (n)-[:PAID*1..{depth}]->(neighbor)
WITH n, neighbor.ACTIVITY AS ACTIVITY, count(*) AS neighborCount
SET n['CREDIT_' + ACTIVITY] = COALESCE(n['CREDIT_' + ACTIVITY], 0) + neighborCount

I'm able to do the count, but then the SET part doesn't work. Any tips on what I'm doing wrong ?

Thanks !

You can’t use dynamic property accessor with a SET operation, only when reading. You can use an apoc method.

1 Like

You could use the following to set the property:

Or, you could get the node’s properties with properites(node), then use this apoc function to update the map, then replace the old properties with the new properties map with a SET operation.