字符串拼接运算符

Cypher® 包含两个用于连接 STRING(字符串)值的运算符。

  • ||

  • +

这两个运算符在功能上是等效的。但是,|| 符合 GQL 标准,而 + 不符合。

有关计算结果为 STRING 值的其他表达式,请参阅 字符串函数

示例

||+
RETURN 'Neo' || '4j' AS result1,
       'Neo' + '4j' AS result2
结果
result1 result2

"Neo4j"

"Neo4j"

行:1

toString() 函数可用于将非 STRING 值连接成 STRING 值。

使用 toString() 函数进行连接
RETURN 'The number is: ' || toString(42) AS result
结果
结果

"The number is: 42"

行:1

在连接 STRING 值时,Cypher 不会自动插入空格。

STRING 连接中添加空格
RETURN 'Alpha' || 'Beta' AS result1,
       'Alpha' || ' ' || 'Beta' AS result2
结果
result1 result2

"AlphaBeta"

"Alpha Beta"

行:1

连接 STRING 属性
CREATE (p:Person {firstName: 'Keanu', lastName: 'Reeves'})
SET p.fullName = p.firstName || ' ' || p.lastName
RETURN p.fullName AS fullName
结果
fullName

"Keanu Reeves"

行:1

STRING 连接中添加分隔符
RETURN 'Hello' || ', ' || 'World' AS result
结果
结果

"Hello, World"

行:1

STRING 连接中添加前缀、后缀和分隔符
RETURN 'My favorite fruits are: ' || 'apples' || ', ' || 'bananas' || ', and ' || 'oranges' || '.' AS result
结果
结果

"My favorite fruits are: apples, bananas, and oranges."

行:1

字符串连接、LIST 值和 null

LIST(列表)中的 STRING 值可以使用 reduce() 函数进行连接。

连接 LIST 中的 STRING
WITH ['Neo', '4j'] AS list
RETURN reduce(acc = '', item IN list| acc || item) AS result
结果
结果

"Neo4j"

行:1

以下查询使用 head() 函数以 list 中的第一个 item 作为累加器的起始值,而 tail() 函数则返回 list 中剩余的项目。然后,reduce() 函数使用逗号将这些项目连接起来。

在由 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
结果
结果

"My favorite fruits are: Apples, Bananas, Oranges."

行: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
结果
结果

"My favorite fruits are: Apples, Bananas, Oranges."

行: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
结果
结果

"My favorite fruits are: Apples, Bananas, Oranges."

"My favorite fruits are: Pears."

"My favorite fruits are: none."

行:3

此外,列表推导式允许将 STRING 值连接到 LIST 中的每一项,从而生成一个新的已修改 STRING 值的 LIST

LIST 项目进行 STRING 连接的列表推导式
WITH ['Apples', 'Bananas', 'Oranges'] AS list
RETURN [item IN list | 'Eat more ' || item || '!'] AS result
结果
结果

["Eat more Apples!", "Eat more Bananas!", "Eat more Oranges!"]

行:1