DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Random Thoughts (Ordering) in Cypher

Random Thoughts (Ordering) in Cypher

Michael Hunger user avatar by
Michael Hunger
·
Apr. 01, 14 · Java Zone · Interview
Like (0)
Save
Tweet
3.42K Views

Join the DZone community and get the full member experience.

Join For Free

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)
RETURN n
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
ORDER BY r
RETURN n

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
ORDER BY name DESC
RETURN o


Database

Published at DZone with permission of , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The 3 Things That Motivate Us
  • When Disaster Strikes: Production Troubleshooting
  • No Code Expectations vs Reality
  • SSH Tutorial: Nice and Easy [Video]

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo