Dragos
Dragos

Reputation: 776

Neo4J Cypher sort descending or ascending according to value

Is there any way to choose between ascending or descending according to a property of a node in a single query?

Let's say I got 2 node types A and B. A has a property specifying how I want to sort B's.

MATCH (a:A)-[:has]->(b:B)
WHERE a.id=1
ORDER BY b.name  ----- (I'd like to order ascending if a.asc is true or descending if false)

Upvotes: 1

Views: 2359

Answers (1)

Gabor Szarnyas
Gabor Szarnyas

Reputation: 5057

You can use UNION, which allows you to combine multiple subqueries to a single query: "It combines the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union."

In this case, depending on the value of a.prop, we do an ascending or a descending ordering.

MATCH (a:A)-[:has]->(b:B)
WHERE a.prop = "x"
RETURN b
ORDER BY b.name ASC
UNION
MATCH (a:A)-[:has]->(b:B)
WHERE a.prop <> "x"
RETURN b
ORDER BY b.name DESC

Upvotes: 2

Related Questions