> ## Documentation Index
> Fetch the complete documentation index at: https://docs.m3ter.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Working with Meter Derived Fields and Examples

The values of Meter Derived Fields are not raw usage data values but always the result of a calculation, which can reference Meter Data Fields, Custom Fields, or Timestamp Fields as source fields. Derived Fields add a very powerful extra dimension of flexibility for setting up the data on which your usage-based pricing plans will be based.

This topic explains the different types of field you can reference in Derived Field calculations, how to format those references in calculations, and offers some Derived Field examples:

* [Referencing Fields in Derived Field Calculations](/guides/usage-data-meters/derived-fields-for-meters-examples-and-supported-syntax#referencing-fields-in-derived-field-calculations)
* [Derived Field Examples](/guides/usage-data-meters/derived-fields-for-meters-examples-and-supported-syntax#derived-field-examples)

<Warning>
  **Important!**

  * If you're reviewing this topic for help in using Derived Field calculations, please also see further details of the supported operators, variables, functions, and type casts at [m3ter Calculation Engine](/guides/m3ter-calculation-engine).
  * You can use [Lookup functions](/guides/lookup-tables/lookup-functions) in your Derived Field calculations and reference Lookup Tables you've created for your Organization. See [Lookup Tables](/guides/lookup-tables) for more details and an example.
</Warning>

## Referencing Fields in Derived Field Calculations

Derived Field calculations will typically reference Meter Data Fields. But you're not restricted to referencing only Meter Data Fields in your calculations. You can also reference *Custom Fields* and *Timestamp Fields,* which greatly extends the scope of measures you can derive and subsequently use as the basis for the Aggregations you need to price your Product Plans.

* [Referencing Data Fields](/guides/usage-data-meters/derived-fields-for-meters-examples-and-supported-syntax#referencing-data-fields)
* [Referencing Custom Fields](/guides/usage-data-meters/derived-fields-for-meters-examples-and-supported-syntax#referencing-custom-fields)
* [Referencing Timestamp Fields](/guides/usage-data-meters/derived-fields-for-meters-examples-and-supported-syntax#referencing-timestamp-fields)

### Referencing Data Fields

The values of Data Fields in the measurement are available as variables, and can be referenced by the Data Field code, for example:

* `myDataField`

### Referencing Custom Fields

You can define Custom Fields for your **Organization** and for the following entity types:

* **Product**
* **Plan Template**
* **Plan**
* **Meter**
* **Account**
* **Account Plan**
* **Aggregation**
* **Compound Aggregation**
* **Contract**

Note that you can define a Custom Field for any of these entities at both the Organizational level and at the level of the individual entity:

* When you reference the Custom Field in a calculation, the value defined for the Custom Field at the Organizational level will be used unless you've also defined a Custom Field at the individual entity level.
* If a Custom Field has also been defined at the individual entity level, this value will be used. This allows you to set up default Custom Field values to use for each entity type in your Organization.

However, restrictions apply to the Custom Fields you can reference in a Derived Field calculation. See [Referencing Custom Fields in Derived Field Calculations](/guides/creating-and-managing-products/working-with-custom-fields#referencing-custom-fields-in-derived-field-calculations) for details.

<Warning>
  **Important!** If you want to use the value of a Custom Field you've defined at an individual entity level, you *must first define* a Custom Field for the entity type at the Organizational level with a default value. For more details, see [Working with Custom Fields](/guides/creating-and-managing-products/working-with-custom-fields).
</Warning>

<Warning>
  **Important!** You can also define Custom Fields for **Aggregations** and **Compound Aggregations**. However, these Custom Fields are NOT supported for referencing in Derived Field calculations.
</Warning>

#### Example - Custom Fields for Accounts

For example, suppose you have five Accounts in your Organization: **Acct1**, **Acct2**, **Acct3**, **Acct4**, and **Acct5**. You expect to use a Derived Field Calculation that will reference a Custom Field for Accounts to add a weighting to each Account for usage data:

* You create a Custom Field for Accounts at the Organization level called `cfAccount` and set its value = **25**.
* You create a Custom Field for **Acct2** called `cfAccount` and set its value = **20**.
* You create a Custom Field for **Acct4** called `cfAccount` and set its value = **30**.
* You do not create any Custom Fields for **Acct1**, **Acct3**, or **Acct5**.

You now reference the Custom Field in your calculation:

* `account.cfAccount`

The calculation will now be evaluated across the five Accounts using these values:

* **Acct1** = **25**
* **Acct2** = **20**
* **Acct3** = **25**
* **Acct4** = **30**
* **Acct5** = **25**

#### Format for Referencing Custom Fields

Here's the general format to use when referencing Custom Fields:

* `organization.<fieldName>`
* `meter.<fieldName>`
* `product.<fieldName>`
* `account.<fieldName>`
* `accountPlan.<fieldName>`
* `plan.<fieldName>`
* `planTemplate.<fieldName>`

<Tip>
  **Tip: Global vs. Product Meters?** Note that Global Meters - those not associated with a Product - cannot resolve Product-scoped Custom Fields, therefore the default will be used. Meters that are associated to a Product can use the Product-specific Custom Field value if it is defined.
</Tip>

<Tip>
  **Tip: See Also?** For creating Custom Fields in the Console, see [Managing your Organization](/guides/organization-and-access-management/viewing-and-editing-organization). You can use the Create/Edit Console pages for individual entities to set up Custom Fields. For API calls, see the [CustomField](/api/customfield/introduction) section of our API Ref Docs. For more background on Custom Fields, see [Working with Custom Fields](/guides/creating-and-managing-products/working-with-custom-fields).
</Tip>

### Referencing Timestamp Fields

You can reference system variable Timestamp Fields in your Derived Field calculations. All timestamps are numeric values representing the appropriate date/times in Epoch milliseconds:

* `ts`
* `ts.startOfMonth`
* `ts.endOfMonth`
* `ts.startOfMonthUTC`
* `ts.endOfMonthUTC`

If the “ets” field - End Timestamp - is specified in the measurement, the following are also available:

* `ets`
* `ets.startOfMonth`
* `ets.endOfMonth`
* `ets.startOfMonthUTC`
* `ets.endOfMonthUTC`

## Derived Field Examples

Please run through the first example as a starter, which shows both the Console setup for the field and the JSON body schema to create the field using a Create Meter API call. Other examples simply give the calculation for the Derived Field:

* [Example 1 - Gigabytes/second measure](https://m3ter.mintlify.app/guides/usage-data-meters/derived-fields-for-meters-examples-and-supported-syntax#example-1-gigabytes/second-measure)
* [Example 2 - Convert GB to MB measure](https://m3ter.mintlify.app/guides/usage-data-meters/derived-fields-for-meters-examples-and-supported-syntax#example-2-convert-gb-to-mb-measure)
* [Example 3 - Convert GB and KB to MB measure](https://m3ter.mintlify.app/guides/usage-data-meters/derived-fields-for-meters-examples-and-supported-syntax#example-3-convert-gb-and-kb-to-mb-measure)
* [Example 4 - MB-mins measure](https://m3ter.mintlify.app/guides/usage-data-meters/derived-fields-for-meters-examples-and-supported-syntax#example-4-mb-mins-measure)
* [Example 5 - String Derived Field operations](https://m3ter.mintlify.app/guides/usage-data-meters/derived-fields-for-meters-examples-and-supported-syntax#example-5-string-derived-field-operations)
* [Example 6 - Derived Fields for Product Add-Ons](https://m3ter.mintlify.app/guides/usage-data-meters/derived-fields-for-meters-examples-and-supported-syntax#example-6-derived-fields-for-product-add-ons)
* [Example 7 - Derived Field for Seat-Based Pricing](https://m3ter.mintlify.app/guides/usage-data-meters/derived-fields-for-meters-examples-and-supported-syntax#example-7-derived-field-for-seat-based-pricing)

In addition to concrete examples, the [final section](/guides/usage-data-meters/derived-fields-for-meters-examples-and-supported-syntax#derived-field-calculations-supported-syntax-and-referencing-fields) in this topic:

* Links you out to a topic on supported syntax and functions for your Derived Field calculations.
* Explains how to reference Custom Fields and system timestamp fields in your Derived Field calculations.

<Tip>
  **Tip: String Derived Fields?** Yes, you can also create non-numeric, string Derived Fields which reference Data Fields. See [Example 5](/guides/usage-data-meters/derived-fields-for-meters-examples-and-supported-syntax#example-5-string-derived-field-operations) below for some examples of operations to create string Derived Fields.
</Tip>

<Warning>
  **Important: Updating the Calculation?** When you use a Derived Field, the calculation is performed at the time the data is ingested and is persisted in the platform at the resultant values. This means that if you update the calculation at a later date:

  * Any calculated values for data ingested *before the update* remain the same.
  * Any calculated values for data ingested *after the update* will be the result of the new calculation.
</Warning>

## Example 1 - Gigabytes/second measure

#### Description and Console Setup

Suppose you run a cloud service which offers your end customers computing capabilities. To implement this service, you want to charge for Products that your end customers consume on the basis of a usage measure in Gigabyte-seconds of processing. To set this up, you can first create two Data Fields of type **Measure** on a Product Meter that ingest raw data measures:

* A **Memory MB** field, which represents the amount of memory in megabytes allocated to the compute function.
* A **Duration** field, which represents the length of time the compute function ran for in milliseconds.

You can then create a Derived Field of type **Measure** on your Product Meter that:

* Converts the input to **Memory MB**, which is in Megabytes (unit: MiBy), to Gigabytes simply by dividing by 1024.
* Converts the input to **Duration,** which is in milliseconds (unit: ms), to seconds simply by dividing by 1000.
* Multiplies the memory allocation in GiBy by the duration value in secs to give a measure in Gigabyte-seconds (unit: GiBy.s):

<img src="https://mintcdn.com/m3ter/4PA7eaLaMtaA6FQv/images/1726065737-createmeter45.png?fit=max&auto=format&n=4PA7eaLaMtaA6FQv&q=85&s=0c9e20f4d096b1a9e285ea49b62e7c9b" style={{ maxWidth:"min(750px, 100%)" }} width="1012" height="891" data-path="images/1726065737-createmeter45.png" />

You can now use this Meter's **GB Second** Derived Field as the basis for setting up an Aggregation for pricing your Product Plans.

<Warning>
  **Important!** Note that when you reference Data Fields in a Derived Field calculation, you must use the **Code** of the referenced fields.
</Warning>

#### Setup using API Call

If you want to create this Meter with the same Data and Derived Fields using an API call, please see our API Reference [Create Meter](/api/meter/create-meter) page. Here's the JSON using this call for the example:

```json theme={null}
{
   "data": [
       {
           "id": "3ddfea4b-XXXX-467d-XXXX-b6YYYYYYYYYf",
           "version": 1,
           "productId": "1b364e59-e32b-4fbf-bc1e-91b5fc4872e5",
           "name": "Compute Execution",
           "code": "compute_execution",
           "dataFields": [
               {
                   "category": "MEASURE",
                   "code": "memory_mb",
                   "name": "Memory MB",
                   "unit": "MiBy"
               },
               {
                   "category": "MEASURE",
                   "code": "duration_ms",
                   "name": "Duration",
                   "unit": "ms"
               }
           ],
           "derivedFields": [
               {
                   "category": "MEASURE",
                   "code": "gb_second",
                   "name": "GB second",
                   "unit": "GiBy.s",
                   "calculation": "(memory_mb/1024)*(duration_ms/1000)"
               }
           ]
       }
   ]
}
```

## Example 2 - Convert GB to MB measure

If you have a Data Field on your Meter that measures gigabytes stored  - field code is `gigabytes_stored` - and you require a megabytes stored measure, then you can create a **Measure** Derived Field and use:

> **Calculation:** `gigabytes_stored*1024`

## Example 3 - Convert GB and KB to MB measure

Suppose you have a Meter with two **Measure** Data Fields for:

* Gigabytes stored: `gigabytes_stored`
* Kilobytes stored: `kilobytes_stored`

If you require a megabytes stored measure that combines these two, then you can create a **Measure** Derived Field and use:

> **Calculation:** `(gigabytes_stored*1024) + (kilobytes_stored/1024)`

## Example 4 - MB-mins measure

Suppose you have a Meter with two Measure Data Fields for:

* Stored volume of data in megabytes at point of last backup: `lastbackup_size`
* Duration since last backup was made in minutes: `lastbackup_duration`

If you require a MB-mins measure, you can create a **Measure** Derived Field and use:

> **Calculation:** `lastbackup_size * lastbackup_duration`

## Example 5 - String Derived Field Operations

You can create string Derived Fields which reference Data Fields. Here's some examples.

#### Concatenation

Suppose you have two string Data Fields on a Meter:

* **Location**, which is a **Where** field used to identify the country of residence of your customers.
* **Type**, which is a **What** field used to identify the type of data check you are performing on your customers.

However, you want a field that combines both these string data types - **Location Type**. To do this, you can use the `+` operator in a Derived Field calculation to concatenate the two string fields:

<img src="https://mintcdn.com/m3ter/Vo1TZsYmBMDUxOdH/images/1662715170-derivedfield1.png?fit=max&auto=format&n=Vo1TZsYmBMDUxOdH&q=85&s=30ce75d8a89a3bd6e06b962a7084c9be" style={{ maxWidth:"min(800px, 100%)" }} width="1097" height="218" data-path="images/1662715170-derivedfield1.png" />

#### Cast Numeric to String

If you need to cast a numeric Data Field as a string to give a string Derived field, you can do this:

<img src="https://mintcdn.com/m3ter/Vo1TZsYmBMDUxOdH/images/1662715778-derivedfield2.png?fit=max&auto=format&n=Vo1TZsYmBMDUxOdH&q=85&s=e16e8eb76fbcedcc5c3f7662f55527c8" style={{ maxWidth:"min(800px, 100%)" }} width="1116" height="236" data-path="images/1662715778-derivedfield2.png" />

<Tip>
  **Tip: String Manipulation Functions?** You can also use String functions in your Derived Field calculations - see [String Functions](/guides/m3ter-calculation-engine#string-functions) for a listing and explanations.
</Tip>

## Example 6 - Derived Fields for Product Add-Ons

Suppose you offer a service to manage and process orders and deliveries for online retailers. Your basic pricing model uses a tiered structure on number of orders/deliveries you handle per billing period. You also want to include some product add-ons, which customers can select for on an order-by-order basis. Pricing for an add-on will use a simple unit price model - each billing period customers are charged a fixed price per add-on consumed.

To meet this pricing use case, you can create a Derived Field that uses the 3-argument  `? :` ternary operator. This operator evaluates a boolean statement as first argument and yields one value if the statement is `TRUE`, another value if the statement is `FALSE`.

In this example:

* We have a string Data Field on a Meter of type **What** called `packaging_design.`
* We then create a Derived Field called `package_addon` of type **Measure**, which uses a calculation that references this Data Field:

> **Calculation:** `packaging_design=="yes"?1:0`

* When an order is placed for processing that takes the add-on, `yes` is entered in the `packaging``*_*``design` field.

The calculation evaluates the first argument to return `TRUE` or `FALSE`:

* If the value of `packaging_design` is `yes`, then the statement is `TRUE` and the value of `package_addon`  is `1`.
* If the value of `packaging_design` is not `yes`, then the statement is `FALSE` and the value of the `package_addon` is `0`.

For pricing, we can now set up an Aggregation that uses the `package_addon` Derived Field as its target field, and then select **SUM** for the Aggregation method.

We can extend this example to show how Derived Fields can be used for use cases where you want to price for a combination of product add-ons. Suppose you want to price when an order you process has opted for an express package delivery and gift packaging as a combined product add-on. You can set up two string Data Fields on a Meter of type **What**:

* `packaging_express`
* `packaging_gift`

You can then use a calculation for a Derived Field of type **Measure** called `package_addon2` that references these two Data Fields and employs a nested ternary operator:

> **Calculation:** `packaging_express=="yes"?(packaging_gift=="yes"?1:0):0`

How does this work?

* The nested expression in brackets is evaluated, which will result in `1` only if `packaging_gift` has a value of `yes`.
* The main expression is then evaluated and results in `1` only if `packaging_express` has a value of `yes` and the nested expression has returned a value of `1`. If the nested expression has returned `0`, then the main expression will return `0`, regardless of whether `packaging_express` has a value of `yes` or any other value - that is, is either `TRUE` or `FALSE`.

We can therefore see how this form of calculation is useful when we want to price for multiple product add-ons as a bundled add-on - only if all referenced Data Fields have a value of `yes` does the Derived Field have a value of `1` returned.

## Example 7 - Derived Field for Seat-Based Pricing

<Tip>
  **Note: Using the m3ter Recurring Charges for Counters feature!** You can also implement seat-based pricing for your products and services out-of-the-box using m3ter's Recurring Charges for Counters feature. See [Recurring Charges: Counters](/guides/recurring-charges-counters) for more details.
</Tip>

Suppose you want to implement usage-based pricing against an end-customer Account which accommodates changes in the number of users on that Account during the billing period. This kind of billing use case is often referred to as "seat-based pricing" and can adjust billing charges in the following way:

* If members are added to the Account at any time within the billing cycle, the Account will be charged a prorated amount based on the percentage of the billing cycle left at the time each member was added.
* If members are removed from the Account at any time within the billing cycle, the Account will be credited in a similar, prorated way.

You can implement seat-based pricing using a Derived Field calculation that uses the 3-argument `? : `ternary operator. This operator evaluates a boolean statement as first argument and yields one value if the statement is `TRUE` , another value if the statement is `FALSE`.

Taking a worked example to illustrate how this calculation works, let's suppose you've put an end-customer Account on a Product Plan for monthly billing and you want to charge for seat-based pricing for September, a 30-day month:

* The Account starts the month at 30 seats.
* 1 seat is removed after 8 days.
* 1 seat was added back in after 20 days.
* This means the seat count is back at 30 at the end of the month.
* The charge rate is \$10 per month per seat on the Account.

For this example:

* The `seat-adjustments` Data Field is used to log either the removal or addition of a single seat and sends in an appropriate value for these events throughout the billing period:
  * A value of -1 when a seat is removed.
  * A value of +1 when a seat is added.
* We then create a Derived Field called `seat_proration` of type Measure that references the `seat_adjustments` field and exploits system `ts` (timestamp) fields:

> **Calculation**: `seat_adjustments * ((ts <= ts.startOfMonth) ? 1 : (ts <= ts.endOfMonth) ? 1 * (((ts.endOfMonth - ts))/(ts.endOfMonth - ts.startOfMonth)) : 0)`

For our worked example, we can first manually calculate what the charge amount should be:

* We have an unchanged seat count of 29 for the full month that results in a charge due of: 29 x \$10 = \$290
* We have a seat count of one that will be charged at the prorate of \$10/30 per day for:
  * 8 days worth: 8 x \$10/30 = \$2.67
  * 10 days worth: 10 x \$10/30 = \$3.33
  * Total charge: \$290 + \$2.67 + \$3.33 = \$296.

We can now breakdown the `seat_proration` Derived Field calculation in the context of the worked example and see how the calculation is evaluated to give a correct prorated seat count value for the month:

* `(ts <= ts.startOfMonth) ? 1`
  * If the `ts` (timestamp) for the `seat_adjustments` event is less than or equal to the start of the month `(ts.startOfMonth)`, the result is 1.
* `(ts <= ts.endOfMonth) ? 1 * (((ts.endOfMonth - ts))/(ts.endOfMonth - ts.startOfMonth)) : 0`
  * In our example, the first `seat_adjustments` event was sent at the end of the 8th day of the Month and this expression checks whether `ts` is less than or equal to the end of the month `(ts.endOfMonth)` which it is. If true, it calculates a weighted value based on the position of `ts` within the month:
    * For the first `seat_adjustment` event,  -1 was sent at the end of the 8th day so the prorated value returned would be -0.73, which represents the reduction in charge due for the 22 days of the month remaining with one seat removed.
    * For the second `seat_adjustment` event, +1 was sent at the start of the 21st day so the prorated value returned would be 0.33, which represents the additional charge due for the 10 days of the month remaining with one seat added back in.
    * This results in a net adjustment of: -0.73 + 0.33 = -0.4

To implement pricing on the Account, we create another Data Field on another Meter:  `start_seatcount`. This sends a measure of the number of seats registered for the Account at the start of each billing period - in our example, the start of each month. With these two Data Fields in place, we can now add Aggregations to arrive at a  pricing metric that accommodates seat count adjustments:

* A simple SUM Aggregation targeting the `start_seatcount` Data Field.
* A simple SUM Aggregation targeting the `seat_proration` Derived Field.
* A Compound Aggregation: `adjusted_seatcount`,  that references these two fields and adds them together them using the following calculation:

> **Calculation:** `(aggregation.start``*_*``seatcount`` ``+ aggregation.seat_proration)`

* We can now use the `adjusted_seatcount` Compound Aggregation to price up Product Plans for those Accounts to which we want to apply seat-based pricing.
* In our concrete example, the result of the calculation used for the  `adjusted_seatcount` Compound Aggregation will be: 30 - 0.4 = 29.60. Therefore the charges for the Account will be: \$10 x 29.60 = \$296, which agrees with what we calculated manually.

In summary, the Derived Field for implementing seat-base pricing calculates a prorated value based on the position of a timestamp (ts) within a month provided by the remove/add usage event.
