Agrimetrics Data Platform

Query Fragments

Sometimes a query will include lots of repetition, for instance getting the same properties for multiple nodes, where the underlying type of the node in each case is the same; using query fragments can minimise how much duplication these queries need.

Example

Consider the following query for various soil properties:

{
  geospatialMeasures(geoFilter: {distance: {LE: 10000}, location: {type: Point, coordinates: [-0.63720703125, 51.09144802136697]}}) {
    soilBacterialDiversity {
      layer {
        id
      }
      value
      unit
      location {
        centroid
      }
    }
    soilPH {
      layer {
        id
      }
      unit
      value
      location {
        centroid
      }
    }
    soilNitrogenConcentration {
      layer {
        id
      }
      unit
      value
      location {
        centroid
      }
    }
  }
}

The same properties are fetched for each soil measurement, resulting in a very verbose query.

However, according to the schema, the properties soilBacterialDiversity, soilPH and soilNitrogenConcentration are all of type SoilMeasure, we can use this fact to help us write a shorter query using fragments.

You can find out the GraphQL type of properties in our schema by hovering over a property in the GraphQL Explorer, or by looking at the inline documentation shown in the GraphQL Documentation Explorer panel, or by asking for the special __typename property of a property when running a query.

Here's the same query with a supporting fragment on SoilMeasure called soilProps:

fragment soilProps on SoilMeasure {
    layer {
      id
    }
    value
    unit
    location {
      centroid
    }
}

query {
  geospatialMeasures(geoFilter: {distance: {LE: 10000}, location: {type: Point, coordinates: [-0.63720703125, 51.09144802136697]}}) {
    soilBacterialDiversity { 
      ...soilProps 
    }
    soilPH { 
      ...soilProps 
    }
    soilNitrogenConcentration {
      ...soilProps 
    }
  }
}

Note that we define the fragment named soilProps outside of the query element, then reference it using the ...soilProps syntax.

You can use multiple fragments in a query, and ask for additional properties alongside them.

Each fragment needs a name which is unique amongst fragments in the request, and must declare on which type it can be used.

Further reading

For more information, see Fragments in the GraphQL learning resource.