Casting data values
Cypher® supports a number of functions to cast values to different data types. This section will provide an overview of those functions, as well examples of how to use them in practice.
Functions for converting data values
The following functions are available for casting data values:
Function | Description |
---|---|
|
Converts a |
|
Converts a |
|
Converts a |
|
Converts an |
|
Converts a |
|
Converts an |
|
Converts a |
|
Converts a |
|
Converts a |
|
Converts an |
|
Converts a |
|
Converts an |
More information about these, and many other functions, can be found in the section on Functions.
Examples
The following graph is used for the examples below:
To recreate it, run the following query against an empty Neo4j database:
CREATE (keanu:Person {name:'Keanu Reeves', age: 58, active:true}),
(carrieAnne:Person {name:'Carrie-Anne Moss', age: 55, active:true}),
(keanu)-[r:KNOWS {since:1999}]->(carrieAnne)
Returning converted values
In the below query, the function toFloat
is used to cast two STRING
values.
It shows that null
is returned if the data casting is not possible.
MATCH (keanu:Person {name:'Keanu Reeves'})
RETURN toFloat(keanu.age), toInteger(keanu.name)
toFloat(keanu.age) | toInteger(keanu.name) |
---|---|
|
|
If the function toFloat
is passed an unsupported value (such as a DATE
value), it will throw an error:
WITH date({
year: 2023, month: 5, day: 2
}) AS d
RETURN toFloat(d)
Type mismatch: expected Float, Integer, Number or String but was Date (line 4, column 16 (offset: 66))
"RETURN toFloat(d)"
However, if the same value is passed to the function toFloatOrNull
, null
will be returned.
WITH date({
year: 2023, month: 5, day: 2
}) AS d
RETURN toFloatOrNull(d)
toFloatOrNull(d) |
---|
|
It is also possible to return casted values as a list.
The below query uses the toStringList
to cast all passed values into STRING
values, and return them in as a LIST<STRING>
:
MATCH (keanu:Person {name:'Keanu Reeves'})
RETURN toStringList([keanu.name, keanu.age]) AS keanuList
keanuList |
---|
|
Updating property value types
The functions to cast data values can be used to update property values on nodes and relationships.
The below query casts the age
(INTEGER
), active
(BOOLEAN
), and since
(INTEGER
) properties to STRING
values:
MATCH (keanu:Person {name:'Keanu Reeves'})-[r:KNOWS]-()
SET keanu.age = toString(keanu.age),
keanu.active = toString(keanu.active),
r.since = toString(r.since)
RETURN keanu.age, keanu.active, r.since
keanu.age | keanu.active | r.since |
---|---|---|
|
|
|