优化 graphql 数据库查询

Optimizing graphql database queries

假设我们有以下 graphql 模式:

type Author : Object {  
  id: ID!
  name: String,
  books: [Book]
}

type Book : Object {  
  id: ID!
  title: String
  authorId: Int
  author: Author
}

然后进行如下查询:

{
    books: {
        id 
        title
        author { id name }
    }
}

例如,如果我们有 10 本书,那么我们将得到 10 个作者查询,因为将为每本获取的书调用 resolve 函数:

select id, name from author where id = 123

我们可以将所有作者查询作为单个查询来执行:

select id, name from author where id in (123, 456, 789, 1011)

是否有一些可行的解决方案、最佳实践、技术或其他可以帮助实现这一目标的东西?

Dataloader 就是您的答案,它具有批处理功能,这意味着它将对所有 ID 进行排队。只有准备好后,它才会批量提取 演示可以在这里找到: https://youtu.be/UBGzsb2UkeY(特别是最后 5 分钟) 算法解释可以在这里找到: https://youtu.be/OQTnXNCDywA

尽情享受吧:)

DataLoader is a great database-agnostic solution. If you're using SQL, Join Monster is more tailored for relational DBs and will even translate the GraphQL queries to SQL directly with a single round-trip. Another alternative is graph-joiner.