字符串连接运算符
示例
|| 和 +RETURN 'Neo' || '4j' AS result1,
'Neo' + '4j' AS result2
| 结果1 | 结果2 |
|---|---|
|
|
行数: 1 |
|
可以使用 toString() 函数将非 STRING 值连接成一个 STRING 值。
使用
toString() 函数进行连接RETURN 'The number is: ' || toString(42) AS result
| 结果 |
|---|
|
行数: 1 |
Cypher 在连接 STRING 值时不会插入空格。
在
STRING 连接中添加空格RETURN 'Alpha' || 'Beta' AS result1,
'Alpha' || ' ' || 'Beta' AS result2
| 结果1 | 结果2 |
|---|---|
|
|
行数: 1 |
|
连接
STRING 属性CREATE (p:Person {firstName: 'Keanu', lastName: 'Reeves'})
SET p.fullName = p.firstName || ' ' || p.lastName
RETURN p.fullName AS 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 |