Can I print out somehow result of rand() function called from Cypher?

49 Views Asked by At

I have the following code:

MATCH (:City {name: 'London'})-[road:Road]->(city:City)
WHERE NOT  city.name IN ['Islington', 'Wembley']
RETURN city.name
ORDER BY road.length ASC
LIMIT 1 + toInteger(7*rand());

On each run I get differnt number of results as I should. I understant that the number of reulsts depend on result of 1 + toInteger(7*rand());. But what I would like to know can I see the result of rand(), which number is genrated? My pseudo code would be somethign like:

LUCKYNUMBER=toInteger(7*rand())
PRINT LUCKYNUMBER
LIMIT 1 + LUCKYNUMBER

I presume that RETURN is the same as PRINT, but how do I create a variable?

1

There are 1 best solutions below

1
On BEST ANSWER

In Cypher, you can create a variable by prefixing the name of the variable with a dollar sign ($). So, you can create the variable LUCKYNUMBER as follows:

WITH toInteger(7*rand()) AS LUCKYNUMBER

You can also use the RETURN statement to return the value of a variable along with the query results, like this:

WITH toInteger(7*rand()) AS LUCKYNUMBER
RETURN LUCKYNUMBER

You can also use the PRINT statement to output the value of a variable to the console, like this:

WITH toInteger(7*rand()) AS LUCKYNUMBER
PRINT LUCKYNUMBER

In your query, you should use WITH statement in order to create a variable, like this:

MATCH (:City {name: 'London'})-[road:Road]->(city:City)
WHERE NOT  city.name IN ['Islington', 'Wembley']
WITH toInteger(7*rand()) AS LUCKYNUMBER
RETURN city.name
ORDER BY road.length ASC
LIMIT 1 + LUCKYNUMBER;

It will create a variable LUCKYNUMBER, store the result of toInteger(7*rand()) in it, and then you can use this variable in your query as you would use any other variable.

This query will return a random number of city names in the range of 1 to 8, and you will see the value of the LUCKYNUMBER variable returned along with the city names.