0
0
GraphQLquery~5 mins

Subgraph definition in GraphQL

Choose your learning style9 modes available
Introduction
A subgraph defines a part of a larger graph to organize and manage data clearly and efficiently.
When you want to split a big graph into smaller, manageable parts.
When different teams work on different parts of the graph.
When you want to reuse parts of the graph in different projects.
When you want to improve performance by loading only needed data.
When you want to clearly define how data connects in a specific domain.
Syntax
GraphQL
type SubgraphName @key(fields: "id") {
  id: ID!
  field1: String
  field2: Int
  relatedField: RelatedType
}
The @key directive marks the unique identifier for the entity.
Fields inside the type define the data structure and relationships.
Examples
Defines a Product entity in a subgraph with a unique 'upc' field.
GraphQL
type Product @key(fields: "upc") {
  upc: String!
  name: String
  price: Int
}
Defines a User entity in a subgraph with 'id' as the unique key.
GraphQL
type User @key(fields: "id") {
  id: ID!
  username: String
  email: String
}
An empty type definition in a subgraph, useful as a placeholder.
GraphQL
type EmptySubgraph {
  # No fields defined yet
}
Sample Program
This example defines two entities in a subgraph schema: Book and Author. Each has a unique key to identify records.
GraphQL
type Book @key(fields: "isbn") {
  isbn: String!
  title: String
  author: Author
}

type Author @key(fields: "id") {
  id: ID!
  name: String
}
OutputSuccess
Important Notes
Subgraphs help organize data in large systems by dividing the graph into smaller parts.
The @key directive is essential to identify unique records in each entity.
Common mistake: forgetting to define a unique key, which can cause data conflicts.
Use subgraphs when you want clear boundaries and ownership of data parts.
Summary
Subgraphs split a big graph into smaller, clear parts.
Each entity in a subgraph needs a unique key using @key directive.
Subgraphs improve data management and team collaboration.