You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Neo4j+GraphQL中为Person类型的friends字段数组添加排序?

Sorting Friend Arrays from Pattern Comprehensions in Neo4j

No problem, I’ve run into this exact scenario before. Pattern comprehensions in Neo4j don’t guarantee ordered results out of the box, so to get your friends array sorted alphabetically (ascending by name), you’ll need to adjust your Cypher query to explicitly sort the friend nodes before collecting them into the array.

Here’s the adjusted Cypher query you should use for your persons resolver:

MATCH (p:Person)
// Match all associated Friend nodes (use OPTIONAL MATCH to keep Persons with no friends)
OPTIONAL MATCH (p)-[:FRIEND_WITH]->(f:Friend)
// Sort the friends by name in ascending order
WITH p, f ORDER BY f.name ASC
// Collect the sorted friends into an array with the required fields
WITH p, COLLECT(f { .id, .name }) AS sortedFriends
// Project the Person object with the sorted friends array
RETURN p { .id, .name, friends: sortedFriends } AS persons
LIMIT $limit

Key Details:

  • OPTIONAL MATCH: Ensures you don’t exclude Persons who have no friends (they’ll just return an empty friends array instead of being omitted entirely).
  • ORDER BY f.name ASC: This is the critical step—we sort each friend by their name before collecting them, so the resulting array maintains this order.
  • COLLECT(): Gathers the sorted Friend nodes into the array that gets assigned to the friends field in your Person projection.

You might have tried adding sorting directly inside the pattern comprehension (like [ (p)-[:FRIEND_WITH]->(f) ORDER BY f.name | f ]), but that’s not valid Cypher syntax. Breaking the process into matching, sorting, then collecting is the standard way to handle ordered arrays in this context.

When you run this query, your friends array will be sorted exactly like your example, with names in A-Z order.

内容的提问来源于stack exchange,提问作者Code Reactor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:23:25