21 Jan 2025
Using Fragments in GraphQL Queries

Introduction
There's a feature that you can take advantage of when using GraphQL queries: Fragments.
One example of a useful scenario is when you need to query specific ElementGroups from the AEC Data Model. With Fragments, you can refer to particular elementgroups/elements by id without duplicated code in your payload.
Thank you Libny Pacheco for bringing this case to us.
How it works
Let's explore the scenario introduced previously.
We need to query the properties of elements from the Walls category in two specific ElementGroups.
Using Fragments, our query could look like the one below:
fragment WallsFilter on ElementGroup{
elements(filter:{query:"property.name.category==Walls"}){
results{
name
properties{
results{
name
value
definition{
units{
name
}
}
}
}
}
}
}
query WallsfromElementGroups($elementGroupIdOne:ID!, $elementGroupIdTwo:ID!){
Snowdon: elementGroupAtTip(elementGroupId:$elementGroupIdOne){
name
...WallsFilter
}
RAC: elementGroupAtTip(elementGroupId:$elementGroupIdTwo){
name
...WallsFilter
}
}
Where the variables would contain your elementgroups ids:
{
"elementgroupIdOne":"YOUR ELEMENTGROUP ID HERE"
"elementgroupIdOne":"YOUR ELEMENTGROUP ID HERE"
}
This approach can be used to improve your queries, removing duplicated content and providing an organized structure.
You can check a complete demo in the video below: