CASE表达式

CASE表达式使用条件来过滤nGQL查询语句的结果,常用于YIELDRETURN子句中。和openCypher一样,nGQL提供两种形式的CASE表达式:简单形式和通用形式。

CASE表达式会遍历所有条件,并在满足第一个条件时停止读取后续条件,然后返回结果。如果不满足任何条件,将通过ELSE子句返回结果。如果没有ELSE子句且不满足任何条件,则返回NULL

简单形式

语法

  1. CASE <comparer>
  2. WHEN <value> THEN <result>
  3. [WHEN ...]
  4. [ELSE <default>]
  5. END
参数说明
comparer用于与value进行比较的值或者有效表达式。
valuecomparer进行比较,如果匹配,则满足此条件。
result如果value匹配comparer,则返回该result
default如果没有条件匹配,则返回该default

示例

  1. nebula> RETURN \
  2. CASE 2+3 \
  3. WHEN 4 THEN 0 \
  4. WHEN 5 THEN 1 \
  5. ELSE -1 \
  6. END \
  7. AS result;
  8. +--------+
  9. | result |
  10. +--------+
  11. | 1 |
  12. +--------+
  1. nebula> GO FROM "player100" OVER follow \
  2. YIELD $$.player.name AS Name, \
  3. CASE $$.player.age > 35 \
  4. WHEN true THEN "Yes" \
  5. WHEN false THEN "No" \
  6. ELSE "Nah" \
  7. END \
  8. AS Age_above_35;
  9. +---------------------+--------------+
  10. | Name | Age_above_35 |
  11. +---------------------+--------------+
  12. | "Tony Parker" | "Yes" |
  13. +---------------------+--------------+
  14. | "LaMarcus Aldridge" | "No" |
  15. +---------------------+--------------+

通用形式

语法

  1. CASE
  2. WHEN <condition> THEN <result>
  3. [WHEN ...]
  4. [ELSE <default>]
  5. END
参数说明
condition如果条件condition为true,表示满足此条件。
resultcondition为true,则返回此result
default如果没有条件匹配,则返回该default

示例

  1. nebula> YIELD \
  2. CASE WHEN 4 > 5 THEN 0 \
  3. WHEN 3+4==7 THEN 1 \
  4. ELSE 2 \
  5. END \
  6. AS result;
  7. +--------+
  8. | result |
  9. +--------+
  10. | 1 |
  11. +--------+
  1. nebula> MATCH (v:player) WHERE v.age > 30 \
  2. RETURN v.name AS Name, \
  3. CASE \
  4. WHEN v.name STARTS WITH "T" THEN "Yes" \
  5. ELSE "No" \
  6. END \
  7. AS Starts_with_T;
  8. +---------------------+---------------+
  9. | Name | Starts_with_T |
  10. +---------------------+---------------+
  11. | "Tim" | "Yes" |
  12. +---------------------+---------------+
  13. | "LaMarcus Aldridge" | "No" |
  14. +---------------------+---------------+
  15. | "Tony Parker" | "Yes" |
  16. +---------------------+---------------+

简单形式和通用形式的区别

为了避免误用简单形式和通用形式,用户需要了解它们的差异。请参见如下示例:

  1. nebula> GO FROM "player100" OVER follow \
  2. YIELD $$.player.name AS Name, $$.player.age AS Age, \
  3. CASE $$.player.age \
  4. WHEN $$.player.age > 35 THEN "Yes" \
  5. ELSE "No" \
  6. END \
  7. AS Age_above_35;
  8. +---------------------+-----+--------------+
  9. | Name | Age | Age_above_35 |
  10. +---------------------+-----+--------------+
  11. | "Tony Parker" | 36 | "No" |
  12. +---------------------+-----+--------------+
  13. | "LaMarcus Aldridge" | 33 | "No" |
  14. +---------------------+-----+--------------+

示例本意为当玩家年龄大于35时输出Yes。但是查看输出结果,年龄为36时输出的却是No

这是因为查询使用了简单形式的CASE表达式,比较对象是.player.age.player.age > 35。当年龄为36时:

  • $$.player.age的值为36,数据类型为int。

  • $$.player.age > 35的值为true,数据类型为boolean。

这两种数据类型无法匹配,不满足条件,因此返回No