Magnus
Magnus

Reputation: 7821

Why is this GraphQL Contentful query too complex?

I get the below error message on a GraphQL query to Contentful, but do not understand why.

Error message:

"Query cannot be executed. The maximum allowed complexity for a query is 11000 but it was 12100. Simplify the query e.g. by setting lower limits for collections."

Query:

query ClassCollection(
  $slug: String
  $limit: Int
) {
  classCollection(
    where: { slug: $slug }
    limit: $limit
  ) {
    items {
      slug
      title
      linkedFrom {
        courseCollection {
          items {
            slug
          }
        }
      }
      filesCollection {
        items {
          title
          asset {
            title
            fileName
            url
            width
            height
            contentType
          }
        }
      }
    }
  }
}

Content model:

Notes

Question

Why am I getting that error message and how can I fix it?

What I tried

EDIT: Calculating the Query Complexity

  1. For the sake of the calculation, let's assume we limit the number of classes, via the query, to 100. So, 100 classes maximum.
  2. Then, since each course can contain a maximum of 10 classes, the maximum number of courses that could be returned is 1,000. I am not sure about this one actually. It has to look at each course, and find the class, which should be 1,000 lookups max.
  3. Each class can only have 10 files at most, giving us a complexity of 1,000 here as well.
  4. That is a maximum complexity of 2,100. I am obviously wrong, since the error message says the complexity is 12,100. Any idea what I am missing?

EDIT 2

Conclusion

Upvotes: 1

Views: 3382

Answers (1)

Ollywood
Ollywood

Reputation: 551

Even if Contentful's GraphQL API is aware of the validation limits for how many Classes in a Course in the linkedFrom field, it is feasible that any other content type in your space that has reference fields may (in theory) also link to a Class, so the query must assume that there can be up to the set limit of linkedFrom entries that aren't Courses.

So your (default) complexity in the query you've shared is:

  • 100 classes
  • 100*100 linkedFrom entries
  • 100*10 files
  • 100*10 asset fields (ie, 1 per file)
  • = 12,100

It may be possible that enforcing validation on ALL reference fields throughout your space to exclude Classes is reflected in the GraphQL response, altho unlikely.

Alternative approaches could be to

  • Limit the query only to classes that are linked from the course reference field (eg something like (where: { linkedFrom: 'courseCollection'})), which might be aware of the validation restriction.
  • Split the query into presentational and relational content - either by requesting the two parts of the Class (files and linkedFrom) separately, or getting the class and file data first and then querying for courses that have that class in their classes field.

Upvotes: 2

Related Questions