Search code examples
neo4jclient

Incorrect sort order with Neo4jClient Cypher query


I have the following Neo4jClient code

var queryItem = _graphClient
        .Cypher
        .Start(new
        {
            n = Node.ByIndexLookup("myindex", "Name", sku),
        })
        .Match("p = n-[r:Relationship]->ci")
         .With("ci , r")
         .Return((ci, r) => new
         {
             N = ci.Node<Item>(),
             R = r.As<RelationshipInstance<Payload>>()
         })
         .Limit(5)
         .Results
         .OrderByDescending(u => u.R.Data.Frequency);

The query is executing fine but the results are not sorted correctly (i.e. in descending order). Here is the Payload class as well.

Please let me know if you see something wrong with my code. TIA.


Solution

  • You're doing the sorting after the .Results call. This means that you're doing it back in .NET, not on Neo4j. Neo4j is returning any 5 results, because the Cypher query doesn't contain a sort instruction.

    Change the last three lines to:

    .OrderByDescending("r.Frequency")
    .Limit(5)
    .Results;
    

    As a general debugging tip, Neo4jClient does two things:

    1. It helps you construct Cypher queries using the fluent interface.
    2. It executes these queries for you. This is a fairly dumb process: we send the text to Neo4j, and it gives the objects back.

    The execution is obviously working, so you need to work out why the queries are different.

    1. Read the doco at http://hg.readify.net/neo4jclient/wiki/cypher (we write it for a reason)
    2. Read the "Debugging" section on that page which tells you how to get the query text
    3. Compare the query text with what you expected to be run
    4. Resolve the difference (or report an issue at http://hg.readify.net/neo4jclient/issues/new if it's a library bug)