如何去除Neo4j字符串数组元素的首尾空格?(示例scor=["1 "," 1"])
Got it, let's tackle how to clean up those leading/trailing spaces in your Neo4j string array. Your example scor=["1 "," 1"] is a perfect case to walk through different solutions.
Using Native Cypher (No External Libraries)
Neo4j’s built-in trim() function handles removing both leading and trailing whitespace from a single string. Pair it with list comprehensions to apply this logic to every element in your array.
Here’s how to use it for your scenario:
// If you're updating a node's array property MATCH (n:YourNodeLabel) SET n.scor = [x IN n.scor | trim(x)] RETURN n.scor; // Test the transformation directly without a node RETURN [x IN ["1 "," 1"] | trim(x)] AS cleaned_scor;
Running this will spit out ["1", "1"]—exactly what you need. The list comprehension loops through each element x in the array, applies trim(), and builds a new cleaned array.
Using APOC Utilities (For Extra Flexibility)
If you have the APOC library installed (a must-have for extended Cypher functionality), you can use apoc.coll.map to achieve the same result. This is great if you want to chain more complex transformations later:
RETURN apoc.coll.map(["1 "," 1"], x -> trim(x)) AS cleaned_scor;
It works just like the native list comprehension, but APOC gives you extra tools for trickier array operations.
Edge Cases to Note
- Handling NULL values:
trim(NULL)returnsNULL, so your cleaned array will retain anyNULLelements. If you want to filter them out, add a condition:RETURN [x IN ["1 ", NULL, " 1"] | trim(x) WHERE x IS NOT NULL] AS cleaned_scor; - Partial trimming: Use
ltrim()if you only need to remove leading spaces, orrtrim()for trailing spaces only.
内容的提问来源于stack exchange,提问作者Suman

