How to execute division using Math API

We have seen a series of posts on Aggregation APIs.

Let’s move on to Math APIs now. In this post, we will check how to divide a field value with a number using Maths API.

  • Math APIs work only on floats and integers, i.e. numerical values.
  • Mathematical operations can only be performed on an existing object.
  • Use the div function to divide the field value of an object with any numerical constant.
  • The quotient gets updated as the new field value.

We will work with the below schema.

type MathObj {
    intFld: Int
    floatFld: Float
}

Let’s insert a few records.

mutation {
  upsert(
    values: {
      MathObj: [
        { intFld: 12, floatFld: 24.24 }
        { intFld: 234, floatFld: 341.21 }
        { intFld: 3455435, floatFld: 1.1 }
       ]
    }
  ) {
    id
  }
}
#result
{
  "data": {
    "upsert": [
      {
        "id": "01FMPZFNHQCVJGNJ6HWWRVNEDP"
      },
      {
        "id": "01FMPZFNHZHF4CFZGFT7CA791F"
      },
      {
        "id": "01FMPZFNJ8YEYVV6APGSTJ4FP1"
      }
    ]
  }
}

Sample Query

Divide the intFld and floatFld values of Hypi objects with constants.

mutation {
  math(
    values: {
      MathObj: [
        { intFld: { hypi: { id: "01FMPZFNHQCVJGNJ6HWWRVNEDP" }, div: 3 } }
        { floatFld: { hypi: { id: "01FMPZFNHQCVJGNJ6HWWRVNEDP" }, div: 3 } }
        { intFld: { hypi: { id: "01FMPZFNHZHF4CFZGFT7CA791F" }, div: 11 } }
        { floatFld: { hypi: { id: "01FMPZFNHZHF4CFZGFT7CA791F" }, div: 2.1 } }
      ]
    }
  ) {
    id
  }
}
#result
{
  "data": {
    "math": [
      {
        "id": "01FMPZFNHQCVJGNJ6HWWRVNEDP"
      },
      {
        "id": "01FMPZFNHQCVJGNJ6HWWRVNEDP"
      },
      {
        "id": "01FMPZFNHZHF4CFZGFT7CA791F"
      },
      {
        "id": "01FMPZFNHZHF4CFZGFT7CA791F"
      }
    ]
  }
} 

Let’s check the resultant values.

{
  find(type: MathObj, arcql: "*") {
    edges {
      node {
        ... on MathObj {
          intFld
          floatFld
        }
      }
      cursor
    }
  }
}
#result
{
  "data": {
    "find": {
      "edges": [
        {
          "node": {
            "intFld": 4,
            "floatFld": 8.08
          },
          "cursor": "01FMPZFNHQCVJGNJ6HWWRVNEDP"
        },
        {
          "node": {
            "intFld": 21,
            "floatFld": 162.48095238095237
          },
          "cursor": "01FMPZFNHZHF4CFZGFT7CA791F"
        },
        {
          "node": {
            "intFld": 3455435,
            "floatFld": 1.1
          },
          "cursor": "01FMPZFNJ8YEYVV6APGSTJ4FP1"
        }
      ]
    }
  }
}

Check the POSTMAN collection for the div query in different programming languages! Click </> and choose the programming language of your choice.
Don’t forget to insert your own Authorization key and Hypi Domain under Headers to test the results!

Run in Postman