创建

这是 GraphQL 库版本 7 的文档。有关长期支持 (LTS) 版本 5,请参考 GraphQL 库版本 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 操作。

  • 变更中存在接口和联合类型。

© . All rights reserved.