字符串拼接运算符
示例
|| 和 +RETURN 'Neo' || '4j' AS result1,
'Neo' + '4j' AS result2
| result1 | result2 |
|---|---|
|
|
行:1 |
|
toString() 函数可用于将非 STRING 值连接成 STRING 值。
toString() 函数进行连接RETURN 'The number is: ' || toString(42) AS result
| 结果 |
|---|
|
行:1 |
在连接 STRING 值时,Cypher 不会自动插入空格。
STRING 连接中添加空格RETURN 'Alpha' || 'Beta' AS result1,
'Alpha' || ' ' || 'Beta' AS result2
| result1 | result2 |
|---|---|
|
|
行:1 |
|
STRING 属性CREATE (p:Person {firstName: 'Keanu', lastName: 'Reeves'})
SET p.fullName = p.firstName || ' ' || p.lastName
RETURN p.fullName AS fullName
| fullName |
|---|
|
行:1 |
STRING 连接中添加分隔符RETURN 'Hello' || ', ' || 'World' AS result
| 结果 |
|---|
|
行:1 |
STRING 连接中添加前缀、后缀和分隔符RETURN 'My favorite fruits are: ' || 'apples' || ', ' || 'bananas' || ', and ' || 'oranges' || '.' AS result
| 结果 |
|---|
|
行:1 |
字符串连接、LIST 值和 null
LIST(列表)中的 STRING 值可以使用 reduce() 函数进行连接。
LIST 中的 STRING 值WITH ['Neo', '4j'] AS list
RETURN reduce(acc = '', item IN list| acc || item) AS result
| 结果 |
|---|
|
行:1 |
LIST 中的 STRING 值连接而成的 STRING 中添加前缀和分隔符 (,)WITH ['Apples', 'Bananas', 'Oranges'] AS list
RETURN 'My favorite fruits are: ' || reduce(acc = head(list), item IN tail(list) | acc || ', ' || item) || '.' AS result
| 结果 |
|---|
|
行:1 |
将 STRING 值与 null 连接会返回 null。要跳过表达式列表中的第一个 null 值,请使用 coalesce() 函数。
在以下查询中,coalesce() 与 reduce() 一起使用,将 LIST 中的每个 null 值替换为空 STRING ('')。这确保了所有 null 值都被有效跳过,从而使 reduce() 函数能够连接剩余的 STRING 值。
reduce() 和 coalesce() 在连接 LIST 时跳过 null 值WITH ['Apples', null, 'Bananas', null, 'Oranges', null] AS list
RETURN 'My favorite fruits are: ' || reduce(acc = head(list), item IN tail(list) | acc || coalesce(', ' || item, '')) || '.' AS result
| 结果 |
|---|
|
行:1 |
如果 LIST 为空,reduce() 将返回 null,因为没有可处理的元素。在这种情况下,可以使用 coalesce() 将 null 替换为默认值(例如 'none')。
reduce() 和 coalesce() 处理空的 LIST 值UNWIND [['Apples', 'Bananas', 'Oranges'], ['Pears'], []] AS list
RETURN 'My favorite fruits are: ' || coalesce(reduce(acc = head(list), item IN tail(list) | acc || ', ' || item), 'none') || '.' AS result
| 结果 |
|---|
|
|
|
行:3 |
此外,列表推导式允许将 STRING 值连接到 LIST 中的每一项,从而生成一个新的已修改 STRING 值的 LIST。
LIST 项目进行 STRING 连接的列表推导式WITH ['Apples', 'Bananas', 'Oranges'] AS list
RETURN [item IN list | 'Eat more ' || item || '!'] AS result
| 结果 |
|---|
|
行:1 |