create

这是 GraphQL Library 7 版本的文档。对于长期支持 (LTS) 版本 5,请参考 GraphQL Library 5 LTS 版本

考虑以下类型定义

type Post @node {
    id: ID! @id
    content: String!
    creator: User! @relationship(type: "HAS_POST", direction: IN)
}

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

以下生成了 create 变更和响应类型

type CreatePostsMutationResponse {
    posts: [Post!]!
}

type CreateUsersMutationResponse {
    users: [User!]!
}

type Mutation {
    createPosts(input: [PostCreateInput!]!): CreatePostsMutationResponse!
    createUsers(input: [UsersCreateInput!]!): CreateUsersMutationResponse!
}

请注意,CreateInput 类型与对象类型定义高度相似。这使得您不仅可以创建所需的类型,还可以向下递归,在同一次变更中对相关类型执行进一步操作。

id 字段在两种 create 输入类型中均不存在,因为已使用 @id 指令。

单个 create

通过执行以下 GraphQL 语句,可以创建单个 User

mutation {
    createUsers(input: [
        {
            name: "John Doe"
        }
    ]) {
        users {
            id
            name
        }
    }
}

这将创建一个名称为 “John Doe” 的 User。返回该名称及自动生成的 ID。

嵌套 create

通过执行以下语句,您可以一次性创建一个 User 及其初始的 Post

mutation {
    createUsers(input: [
        {
            name: "John Doe"
            posts: {
                create: [
                    {
                        node: {
                            content: "Hi, my name is John!"
                        }
                    }
                ]
            }
        }
    ]) {
        users {
            id
            name
            posts {
                id
                content
            }
        }
    }
}

这将创建一个名称为 “John Doe” 的 User 和一篇介绍性帖子。两者都会返回其自动生成的 ID。

欲了解更多关系操作示例,请参阅 关系操作

create 优化

使用 create 操作时,一次可以创建任意数量的节点。然而,对于大批量时存在已知的性能问题。

Neo4j GraphQL 库提供了一项用于缓解该问题的优化功能,但在以下场景下无法生效。

  • 字段是通过指令 @populated_by 填充的。

  • 使用了 connect 操作。

  • 变更中出现了接口和联合类型。