Frank.H
Frank.H

Reputation: 13

How string item order in neo4j

I ran a Cypher query with the clause:

ORDER BY xxx DESC

where xxx is a string, like ["Coyote"," Eastern Coyote"]. I want it ordered with first alphabet ASC, like this: [" Eastern Coyote","Coyote"]. but the outcome is still this: ["Coyote"," Eastern Coyote"].

FYI: i asked chatgpt,it said order in neo4j is depends on alphabet's unicode, but it still not make sense, cause "E" is Larger than "C"

Upvotes: 0

Views: 165

Answers (2)

cybersam
cybersam

Reputation: 66989

In your question, you made some major mistakes:

  1. ["Coyote"," Eastern Coyote"] is a list of strings, not a string.

  2. ORDER BY xxx DESC sorts in descending order, not ascending.

  3. You said:

    ... still not make sense, cause "E" is Larger than "C"

    But the string " Eastern Coyote" actually starts with a space character, so you should have been comparing " " to "C". The " " character has a lower lexical value than "C". Therefore, ["Coyote"," Eastern Coyote"] is the correct answer after sorting the list items in descending order.

You need to double-check your string values to remove extraneous spaces.

Also, to return a list of the strings from xxx in ascending order (which is the default order), you can use this snippet:

...
UNWIND xxx AS y
WITH y ORDER BY y
RETURN COLLECT(y) AS result

Or, if you really want to return the list in descending order:

...
UNWIND xxx AS y
WITH y ORDER BY y DESC
RETURN COLLECT(y) AS result

Upvotes: 0

jose_bacoy
jose_bacoy

Reputation: 12684

You can sort the items on the list in below examples:

  1. Using UNWIND and COLLECT
    WITH  [ "Coyote"," Eastern Coyote"]  as lst
    UNWIND lst as l
    WITH l ORDER by l
    RETURN  collect(l) as sorted_lst
  1. Using apoc function sort
    WITH  [ "Coyote"," Eastern Coyote"]  as lst
    RETURN apoc.coll.sort(lst) as sorted_lst

Result:

╒════════════════════════════╕
│"sorted_lst"                │
╞════════════════════════════╡
│[" Eastern Coyote","Coyote"]│
└────────────────────────────┘

Upvotes: 0

Related Questions