Search code examples
neo4jcypher

Neo4J conditional formatting of a string attribute from a set of boolean attributes


I have a node with the following attributes :

MyNode
  stage_1: boolean
  stage_2: boolean
  stage_3: boolean

I'd like to create a query that generate a macro_step string attribute, that is conditionnally filled by the values of the booleans. For instance, if stage_1 and stage_3 were true but stage_2false, I would like MyNode.macro_steps to be filled with "STAGE_1 STAGE2"

I tried the following but it doesn't work :

match (mo:MyNode)
mo.macro_steps = ""
case
  when mo.stage_1 then mo.macro_steps += "STAGE_1\n"
  when mo.stage_2 then mo.macro_steps += "STAGE_2\n"
  // etc.
  else null
end
return mo

How can I achieve this ?


Solution

  • Try this:

    MATCH (n:MyNode)
    WITH n, 
    reduce(str = '', propertyKey IN keys(properties(n)) | 
    CASE WHEN n[propertyKey] = true THEN str + toUpper(propertyKey) + " " 
         WHEN n[propertyKey] = false THEN str + toUpper(replace(propertyKey, '_', '')) + " " 
         ELSE str END) AS macro_steps
    SET n.macro_steps = trim(macro_steps)
    RETURN n
    

    For the node, created by:

    MERGE (r:MyNode{sample_1: true, sample_2: true, sample_3: false})
    

    The first query gives:

    ╒══════════════════════════════════════════════════════════════════════╕
    │"n"                                                                   │
    ╞══════════════════════════════════════════════════════════════════════╡
    │{"sample_1":true,"sample_2":true,"sample_3":false,"macro_steps":"SAMPL│
    │E_1 SAMPLE_2 SAMPLE3"}                                                │
    └──────────────────────────────────────────────────────────────────────┘
    

    As suggested by @nimrodserok, in the comments, if you only want true valued property keys, then this is the query:

    MATCH (n:MyNode) 
    WITH n,  reduce(str = '', propertyKey IN keys(properties(n)) |  
    CASE WHEN n[propertyKey] = true THEN str + toUpper(propertyKey) + ' '
         ELSE str END) AS macro_steps 
    SET n.macro_steps = trim(macro_steps) 
    RETURN n
    

    The output is:

    {"stage_1":true,"stage_2":false,"stage_3":true,"macro_steps":"STAGE_1 STAGE_3"}