Search code examples
neo4jcypher

In Cypher can I check if a property is a list before updating its value


We are updating data in a database and for some nodes, because of legacy data, we might find a property as a string or as a list. I would like to convert strings into an empty list and keep lists as is. I have tried something like this :

MATCH (a:part) WHERE NOT EXISTS((a.serials)[0]) SET a.serials=[] return a

but it just throws an error.

any idea?


Solution

  • Cypher has no built-in function for this but there is a small hack you can use that is checking if adding an element to the property would increase its size by 1 , for eg

    MATCH (n:Award)
    RETURN size(n.years + 11) = size(n.years)+1 AS isList
    

    + sign, add elements, concat or sums. Therefore to differentiate a a string from an array, we need to add two digits.


    UPDATE FOR NEO4J5

    Neo4j 5.10 introduced type predicate expressions for list types, example :

    CREATE (n:Node {id: 1}) SET n.roles = ['roleA', 'roleB']
    RETURN n.roles IS :: LIST<ANY>
    

    More information here : https://neo4j.com/docs/cypher-manual/current/values-and-types/type-predicate/#type-predicate-lists