Search code examples
neo4jcypher

What is the literal expression of NaN in Neo4j Cypher?


How do I express NaN as a literal in a Cypher query?

Situation

I have a NaN value in a database:

match (a) with max(a.CONCENTRATION) as m return m

will return

m
---
NaN

Cypher reference in Neo4j mentioned that this is possible as the result of special value being stored:

The special value java.lang.Double.NaN is regarded as being larger than all other numbers.

What I tried

However, now that it's in there, I don't know how to match them in search, because you get the following error

input

match (a) where a.CONCENTRATION = NaN return a limit 10

error

Variable `NaN` not defined (line 1, column 35 (offset: 34))

Other references

Cypher reference in Neo4j doesn't mention NaN literal, unless I missed it.

I've googled 'Cypher NaN' but the closest thing I got is how to add inf/NaN, which wasn't directly addressed (How to add infinity, NaN, or null values to a double[] property on a node in Cypher/Neo4j).


Solution

  • [UPDATE 2]

    Neo4j 5.0 introduced:

    • the float literals Inf, Infinity, and NaN.
    • the isNaN() function for determining whether the specified value is NaN.

    [ORIGINAL]

    There is no way to specify the literal, but this should work:

    MATCH (a)
    WHERE TOFLOAT(a.CONCENTRATION) <> a.CONCENTRATION
    RETURN a
    LIMIT 10;
    

    TOFLOAT() will return NULL if the argument cannot be converted (as needed) to a number. But, even if the argument can be converted, the result would not equal the argument unless it was numeric to begin with.

    [UPDATE 1]

    @chaserino's nice new answer prompted me to do a little more experimentation.

    Although there is still no literal for NaN, Infinity, and -Infinity, I determined that Cypher can generate those values in neo4j version 3.4.0+ (I did not test earlier versions). You can then use those values for comparison purposes.

    For example, this query shows how to generate those values:

    RETURN 0.0/0.0, 1.0/0.0, -1.0/0.0
    

    And here is the result:

    ╒═════════╤═════════╤══════════╕
    │"0.0/0.0"│"1.0/0.0"│"-1.0/0.0"│
    ╞═════════╪═════════╪══════════╡
    │NaN      │Infinity │-Infinity │
    └─────────┴─────────┴──────────┘
    

    NOTE: For Infinity, you can actually use any positive numerator, and for -Infinity, you can use any negative numerator.