天天看点

Neo4j Cypher CASE语句

在Cypher的语法中常见的CASE语句有两种:

Simple CASE form

Generic CASE form

。官方给的解释是:

Simple CASE form: comparing an expression against multiple values;

Generic CASE form: allowing for multiple conditionals to be expressed;

CASE语句的作用是:如果满足条件语句中的条件,则返回此条件的结果;否则返回

ELSE

的结果;如果CASE语句中没有

ELSE

,则返回

null

换句话说,CASE语句与编程语言中的

IF...ELSE..

语句类似

**

Simple CASE form

**

syntax

CASE test
    WHEN value THEN result
    [WHEN ...]
    [ELSE default]
END
           

Arguments

Name Description
test A valid expression
value An expression whose result will compared to test
result This is the expression returned as output if value matches test
default if not match is found, default is returned

For Example

MATCH (n)
RETURN
CASE n.eyes
WHEN 'blue'
THEN 1
WHEN 'brown'
THEN 2
ELSE 3 END AS result
           

**

Generic CASE form

**

syntax

CASE
WHEN predicate THEN result
    [WHEN ...]
    [ELSE default]
END
           

Arguments

name Description
predicate A predicate that is tested to find a valid alternative.
result This is the expression returned as output if predicate evaluates to true.
default if no match is found, default is returned.

For Example

MATCH (n)
RETURN
CASE
WHEN n.eyes == 'blue'
THEN 1
WHEN n.age < 40
THEN 2
ELSE 3 END AS result
           

**

区分何时使用Generic CASE form,何时使用Simple CASE form

**

问题:

假如,我们需要输出所有用户10年前的年龄,如果年龄属性为空,则输出-1,否则输出年龄age-10

Simple CASE

MATCH (n)
RETURN n.name,
CASE n.age
WHEN n.age IS NULL THEN -1
ELSE n.age - 10 END AS age_10_years_ago
           

如果采用此种方法,

WHEN n.age IS NULL THEN -1

条件语句将永远不会被执行。因为

n.age

Integer

类型,而

n.age is NULL

是布尔类型。所以会执行

ELSE n.age - 10 END AS age_10_years_ago

,返回

null

Generic CASE

MATCH (n)
RETURN n.name,
CASE
WHEN n.age IS NULL THEN -1
ELSE n.age - 10 END AS age_10_years_ago
           

将返回正确的结果

继续阅读