SledgeHammer
SledgeHammer

Reputation: 7736

Neo4j ORDER BY custom sorting?

I have a query where a part of it looks like:

WITH ... person ORDER BY person.name

The issue is that person.name contains the full name i.e. "Albert Einstein". So Albert Einstein appears before "Peter Albert".

Is there a way to do the order by on the persons last name? I.e. some kind of custom comparator? Of course, taking into account one name people like Madonna :).

I know I could go into the data and split all the names, but I'd like to avoid doing that if possible.

Upvotes: 0

Views: 526

Answers (1)

jose_bacoy
jose_bacoy

Reputation: 12714

You can sort on the fly but as stated in the comments, it will be expensive compared to splitting the data in the model.

Using the Movies dataset as example, here is a way to sort it based on last name. Split the name separated by space into a list then [-1] means sort by the last item of that list.

MATCH (n:Person) 
WITH n ORDER by split(n.name, ' ')[-1]
RETURN n.name

result:

 ════════════════════════╕
│"n.name"                │
╞════════════════════════╡
│"Stefan Arndt"          │
├────────────────────────┤
│"Kevin Bacon"           │
├────────────────────────┤
│"Christian Bale"        │
├────────────────────────┤
│"Marshall Bell"         │
├────────────────────────┤
│"Halle Berry"           │

Upvotes: 1

Related Questions