user3415585
user3415585

Reputation: 21

Preserve order of match query based on input array

If I do

UNWIND ['3','1','2'] AS id MATCH (director:Director)-[:DIRECTED]->(movie:Movie {id:id}) return movie, director

Movies come in order [3, 1, 2] but when I change my query and try to get more information like below

UNWIND ['3','1','2'] AS id MATCH (director:Director)-[:DIRECTED]->(movie:Movie {id:id}) with director, movie OPTIONAL MATCH (movie)<-[actors:ACTED_IN]-() return movie, director, count(actors)

order gets something different than [3, 1, 2]. How should change second query so that I can preserve the order of input array?

Upvotes: 2

Views: 344

Answers (3)

AlexAlfaroA.
AlexAlfaroA.

Reputation: 21

If you want to control the order of the output based on the order in a list of parameters try passing an array of objects, like this:

UNWIND [{id:'3',order:1},{id:'1',order:2},{id:'2',order:3}] AS param
MATCH (director:Director)-[:DIRECTED]->(movie:Movie {id:param.id})
WITH param.order AS o, movie AS m, director AS d
ORDER BY o
RETURN m, d;

I haven't run the query, but that's the way I solved that.

Upvotes: 2

Richard G&#252;nzl
Richard G&#252;nzl

Reputation: 124

I tried similar situation and it works. You can try something like this:

UNWIND ['3','1','2'] AS id 
MATCH (director:Director)-[:DIRECTED]->(movie:Movie {id:id}) 
WITH id, director, movie 
OPTIONAL MATCH (movie)<-[actors:ACTED_IN]-() 
RETURN id, movie, director, count(actors)

It fixes final order by the UNWIND order. There is very important placement in RETURN clause. id has to be the first.

Upvotes: 1

FrobberOfBits
FrobberOfBits

Reputation: 18002

Never depend on any default ordering with cypher queries. When you match, the results come back in any order that suits cypher, and there's no guarantee the language would provide you there. This is actually a good feature, not a bug - it frees cypher to go get things in whichever order might be most efficient. You haven't explicitly specified an order, so whatever cypher does is I think correct against the spec of what the language is supposed to do.

Now to answer your direct question, if you wanted your results ordered a particular way, you should use an ORDER BY clause.

That would be easy with your first query, just tack on ORDER BY movie.id DESC at the end, and you're done.

What's odd about your second query though is that you don't include movies in the return clause. You'd need to be more specific about what you mean by ordering things in terms of a value that isn't implicated in the return clause.

Upvotes: 1

Related Questions