聚合

这是 GraphQL 库版本 7 的文档。有关长期支持 (LTS) 版本 5,请参阅GraphQL 库版本 5 LTS

类型定义

此页面中的查询假设以下类型定义

type Post @node {
    id: ID! @id
    content: String!
    creators: [User!]! @relationship(type: "HAS_POST", direction: IN, properties: "PostedAt")
    createdAt: DateTime!
}

type User @node {
    id: ID! @id
    name: String!
    age: Int!
    posts: [Post!]! @relationship(type: "HAS_POST", direction: OUT, properties: "PostedAt")
    friends: [User!]! @relationship(type: "FRIENDS_WITH", direction: OUT)
}

type PostedAt @relationshipProperties {
    date: DateTime
}

为此生成以下查询字段

type Query {
    posts(where: PostWhere, sort: [PostSort!]!, limit: Int, offset: Int,): [Post!]!
    postsConnection(after: String, first: Int, sort: [PostSort], where: PostWhere): PostsConnection!
    users(where: UserWhere, sort: [UserSort!]!, limit: Int, offset: Int,): [User!]!
    usersConnection(after: String, first: Int, sort: [UserSort], where: UserWhere): UsersConnection!
}

查询聚合

类型的聚合在 Connection 内部的 aggregate 字段中提供

query {
    usersConnection {
        aggregate {
            name {
                longest
            }
        }
    }
}

聚合字段

根据类型定义,以下是 Neo4j GraphQL 支持的接受聚合的字段列表

类型 聚合函数 示例

字符串 (例如 ID, String)

shortest, longest

最长的用户名称
query {
    usersConnection {
        aggregate {
            name {
                longest
            }
        }
    }
}

时态 (例如 DateTime, Time, LocalTime, LocalDateTime, Duration)

min, max

最早的帖子日期
query {
    postsConnection {
        aggregate {
            createdAt {
                min
            }
        }
    }
}
计数用户节点
query {
    usersConnection {
        aggregate {
            count {
                nodes
            }
        }
    }
}
计数名称以“J”开头的用户节点
query {
    usersConnection(where: { name: { startsWith: "J" } }) {
        aggregate {
            count {
                nodes
            }
        }
    }
}

您可以通过访问连接中的聚合字段来在查询中聚合相关节点。在这些字段中,您可以计数、聚合节点字段。

聚合字段中相同的选择和类型在关系聚合中可用。

计数每个用户的帖子总数
query {
    users {
        id
        postsConnection {
            aggregate {
                count {
                    nodes
                }
            }
        }
    }
}

通过使用 node 字段,可以聚合相关节点的属性

查找每个用户最长的帖子
query {
    users {
        name
        postsConnection {
            aggregate {
                node {
                    content {
                        longest
                    }
                }
            }
        }
    }
}

聚合关系

通过使用 edge 字段,也可以聚合关系属性

计数帖子和用户之间的边
query {
    users {
        id
        postsConnection {
            aggregate {
                count {
                    edges
                }
            }
        }
    }
}
查询用户节点在某个日期之前发布了什么
query {
    users {
        name
        postsConnection {
            aggregate {
                edge {
                    date {
                        max
                    }
                }
            }
        }
    }
}
© . All rights reserved.