janwo
janwo

Reputation: 754

Confused about using ORDER BY correctly

I am experimenting with dates in neo4j. Now I'd like to sort my results by the ISODateString. I created a cypher query like this:

MATCH(e:Expedition {id : "BJGYmzwZb"})-[pje]-(u:User) 
WHERE (e)-[:POSSIBLY_JOINS_EXPEDITION]-(u) OR (e)-[:JOINS_EXPEDITION]-(u) 
WITH e, u, apoc.date.parse(pje.createdAt, 's',"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") as date
ORDER by date 
OPTIONAL MATCH(u)<-[invitee:POSSIBLY_JOINS_EXPEDITION]-(e) 
OPTIONAL MATCH(u)-[attendee:JOINS_EXPEDITION]->(e)
OPTIONAL MATCH(u)-[applicant:POSSIBLY_JOINS_EXPEDITION]->(e) 
RETURN date, {user: properties(u), isInvitee: COUNT(invitee) > 0, isApplicant: COUNT(applicant) > 0, isAttendee: COUNT(attendee) > 0} as u

The returned results are not sorted properly. Whereas the following query does return the results in the right order. I just removed the parts with OPTIONAL MATCH.

MATCH(e:Expedition {id : "BJGYmzwZb"})-[pje]-(u:User) 
WHERE (e)-[:POSSIBLY_JOINS_EXPEDITION]-(u) OR (e)-[:JOINS_EXPEDITION]-(u) 
WITH e, u, apoc.date.parse(pje.createdAt, 's',"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") as date 
ORDER by date
RETURN date, {user: properties(u)} as u

Any suggestions what I am doing wrong? Do I need to deal differently with the OPTIONAL MATCH-additions?

Upvotes: 0

Views: 56

Answers (1)

Bruno Peres
Bruno Peres

Reputation: 16365

Put ORDER by date after the RETURN statement, like this:

MATCH(e:Expedition {id : "BJGYmzwZb"})-[pje]-(u:User) 
WHERE (e)-[:POSSIBLY_JOINS_EXPEDITION]-(u) OR (e)-[:JOINS_EXPEDITION]-(u) 
WITH e, u, apoc.date.parse(pje.createdAt, 's',"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") as date
OPTIONAL MATCH(u)<-[invitee:POSSIBLY_JOINS_EXPEDITION]-(e) 
OPTIONAL MATCH(u)-[attendee:JOINS_EXPEDITION]->(e)
OPTIONAL MATCH(u)-[applicant:POSSIBLY_JOINS_EXPEDITION]->(e) 
RETURN date, {user: properties(u), isInvitee: COUNT(invitee) > 0, isApplicant: COUNT(applicant) > 0, isAttendee: COUNT(attendee) > 0} as u
ORDER by date 

Upvotes: 1

Related Questions