DZone
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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Alpha Testing Tutorial: A Comprehensive Guide With Best Practices
  • Designing a New Framework for Ephemeral Resources
  • How Agile Works at Tesla [Video]
  • Integrating AWS With Salesforce Using Terraform

Trending

  • Alpha Testing Tutorial: A Comprehensive Guide With Best Practices
  • Designing a New Framework for Ephemeral Resources
  • How Agile Works at Tesla [Video]
  • Integrating AWS With Salesforce Using Terraform
  1. DZone
  2. Data Engineering
  3. Databases
  4. Neo4j and Cypher: Profiling ORDER BY LIMIT vs. LIMIT

Neo4j and Cypher: Profiling ORDER BY LIMIT vs. LIMIT

Mark Needham user avatar by
Mark Needham
·
Oct. 29, 13 · Interview
Like (0)
Save
Tweet
Share
5.26K Views

Join the DZone community and get the full member experience.

Join For Free

Something I’ve seen people get confused by when writing queries using Neo4j’s cypher query language is the sometimes significant difference in query execution time when using ‘LIMIT’ on its own compared to using it in combination with ‘ORDER BY’.

The confusion is centered around the fact that at first glance it seems like the only thing different between these queries is the sorting of the rows, but there’s actually more to it.

For example, given a small graph with ~ 11,000 nodes…

$ MATCH n RETURN COUNT(n);
 
==> +----------+
==> | COUNT(n) |
==> +----------+
==> | 11442    |
==> +----------+
==> 1 row
==> 1384 ms

…we can return 5 random nodes really quickly with the following query:

$ MATCH n RETURN n LIMIT 5;
 
==> +-------------------------------------------+
==> | n                                         |
==> +-------------------------------------------+
==> | Node[0]{}                                 |
==> | Node[1]{name:"Africa",node_id:"1"}        |
==> | Node[2]{name:"Asia",node_id:"2"}          |
==> | Node[3]{name:"Europe",node_id:"3"}        |
==> | Node[4]{name:"North America",node_id:"4"} |
==> +-------------------------------------------+
==> 5 rows
==> 38 ms

However, if we order those nodes by ID first then it’ll take a bit longer:

$ MATCH n RETURN n ORDER BY ID(n) LIMIT 5;
==> +-------------------------------------------+
==> | n                                         |
==> +-------------------------------------------+
==> | Node[0]{}                                 |
==> | Node[1]{name:"Africa",node_id:"1"}        |
==> | Node[2]{name:"Asia",node_id:"2"}          |
==> | Node[3]{name:"Europe",node_id:"3"}        |
==> | Node[4]{name:"North America",node_id:"4"} |
==> +-------------------------------------------+
==> 5 rows
==> 157 ms

If we have a look at the profile of the second query we can see why this is:

$ PROFILE MATCH n RETURN n ORDER BY ID(n) LIMIT 5;
 
==> ColumnFilter(symKeys=["n", "  UNNAMEDS1215244997"], returnItemNames=["n"], _rows=5, _db_hits=0)
==> Top(orderBy=["SortItem(Cached(  UNNAMEDS1215244997 of type Long),true)"], limit="Literal(5)", _rows=5, _db_hits=0)
==>   Extract(symKeys=["n"], exprKeys=["  UNNAMEDS1215244997"], _rows=11442, _db_hits=0)
==>     AllNodes(identifier="n", _rows=11442, _db_hits=11442)

Top refers to TopPipe and if we look at the internalCreateResults function we can see that the entire collection gets evaluated so that we can sort it correctly on line 63.

if (input.isEmpty)
      Iterator.empty
    else {
      val first = input.next()
      val count = countExpression(first).asInstanceOf[Number].intValue()
 
      val iter = new HeadAndTail(first, input)
      iter.foreach {
        case ctx =>
 
          if (size < count) {
            result += ctx
            size += 1
 
            if (largerThanLast(ctx)) {
              last = Some(ctx)
            }
          } else
            if (!largerThanLast(ctx)) {
              result -= last.get
              result += ctx
              result = result.sortWith((a, b) => compareBy(a, b, sortDescription)(state))
              sorted = true
              last = Some(result.last)
            }
      }
    }

In this case, it means that we load the next node, but in a more complex query, we’d have to evaluate a more complex pattern for every single match.

On the other hand, if we don’t have the ‘ORDER BY’ we use the SlicePipe which does a take on the iterator which lazily retrieves the first 5 results in this instance:

$ PROFILE MATCH n RETURN n LIMIT 5;
 
==> Slice(limit="Literal(5)", _rows=5, _db_hits=0)
==> AllNodes(identifier="n", _rows=5, _db_hits=5)
(skip, limit) match {
      case (Some(x), None) => sourceIter.drop(asInt(x))
      case (None, Some(x)) => sourceIter.take(asInt(x))
 
      case (Some(startAt), Some(count)) =>
        val start = asInt(startAt)
        sourceIter.slice(start, start + asInt(count))
 
      case (None, None) =>
        throw new ThisShouldNotHappenError("Andres Taylor", "A slice pipe that doesn't slice should never exist.")
    }

Now that we’ve drilled into the queries a bit more, we can see that with the ‘ORDER BY LIMIT’ query, many more paths need to be evaluated to make that possible.

A common anti-pattern is to return a result set containing hundreds of thousands of rows and then using ‘ORDER BY LIMIT’ to filter that down to 10.

In that case, there might be a better way of modelling the data so that we have fewer rows coming back from our MATCH clause, and In graph indexes are one such way of doing that.


Database Neo4j

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

Opinions expressed by DZone contributors are their own.

Trending

  • Alpha Testing Tutorial: A Comprehensive Guide With Best Practices
  • Designing a New Framework for Ephemeral Resources
  • How Agile Works at Tesla [Video]
  • Integrating AWS With Salesforce Using Terraform

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • 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

Let's be friends: