Over a million developers have joined DZone.

Random Thoughts (Ordering) in Cypher

DZone's Guide to

Random Thoughts (Ordering) in Cypher

· Java Zone ·
Free Resource

Delivering modern software? Atomist automates your software delivery experience.

There was a question on the Neo4j Google Group about returning results in a random order in Cypher. So I thought explaining it in a blog post (this) and an interactive GraphGist is better than just to answer the email.

The naive approach is just to order by rand():

MATCH (n:Crew)
ORDER BY rand()

Which fails with:

ORDER BY expressions must be deterministic. For instance, you cannot use the rand() function in the expression

That’s explainable, how would you order by something that generates a new value on each call. So we have to associate a random value with each row. Fortunately that’s easy with WITH:

MATCH (n:Crew)
WITH n, rand() AS r

So WITH n, rand() as r adds a new column called r (we need the alias) to each row, then we can order by that as part of with (we could even paginate) but in the RETURN clause we only return n and don’t expose r.

This approach is also handy if you want to order by things that you don’t want to expose later on.

Like ordering by the name of the person, but returning the friends in that order:

MATCH (n:Crew)-[:KNOWS]->(o)
WITH n.name as name, o

Start automating your delivery right there on your own laptop, today! Get the open source Atomist Software Delivery Machine.

java ,nosql ,tips and tricks ,neo4j ,cypher ,tools & methods

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}