# MathExpression

A math expression built with metric(s) emitted by a service.

The math expression is a combination of an expression (x+y) and metrics to apply expression on.
It also contains metadata which is used only in graphs, such as color and label.
It makes sense to embed this in here, so that compound constructs can attach
that metadata to metrics they expose.

MathExpression can also be used for search expressions. In this case,
it also optionally accepts a searchRegion and searchAccount property for cross-environment
search expressions.

This class does not represent a resource, so hence is not a construct. Instead,
MathExpression is an abstraction that makes it easy to specify metrics for use in both
alarms and graphs.

Implements: [IMetric](/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.IMetric.html)
Obtainable from: [Metric.anomalyDetectionFor](/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.Metric.html#anomalydetectionfor)

- Source: [`aws-cloudwatch/lib/metric.ts`](https://github.com/aws/aws-cdk/blob/v2.277.0/packages/aws-cdk-lib/aws-cloudwatch/lib/metric.ts#L791)
- Type last changed: v2.276.0 · 10 Nov 2026

## Example

TypeScript:

```ts
declare const matchmakingRuleSet: gamelift.MatchmakingRuleSet;
// Alarm that triggers when the per-second average of not placed matches exceed 10%
const ruleEvaluationRatio = new cloudwatch.MathExpression({
  expression: '1 - (ruleEvaluationsPassed / ruleEvaluationsFailed)',
  usingMetrics: {
    ruleEvaluationsPassed: matchmakingRuleSet.metricRuleEvaluationsPassed({ statistic: cloudwatch.Statistic.SUM }),
    ruleEvaluationsFailed: matchmakingRuleSet.metric('ruleEvaluationsFailed'),
  },
});
new cloudwatch.Alarm(this, 'Alarm', {
  metric: ruleEvaluationRatio,
  threshold: 0.1,
  evaluationPeriods: 3,
});
```

Python:

```python
# matchmaking_rule_set: gamelift.MatchmakingRuleSet

# Alarm that triggers when the per-second average of not placed matches exceed 10%
rule_evaluation_ratio = cloudwatch.MathExpression(
    expression="1 - (ruleEvaluationsPassed / ruleEvaluationsFailed)",
    using_metrics={
        "rule_evaluations_passed": matchmaking_rule_set.metric_rule_evaluations_passed(statistic=cloudwatch.Statistic.SUM),
        "rule_evaluations_failed": matchmaking_rule_set.metric("ruleEvaluationsFailed")
    }
)
cloudwatch.Alarm(self, "Alarm",
    metric=rule_evaluation_ratio,
    threshold=0.1,
    evaluation_periods=3
)
```

Java:

```java
MatchmakingRuleSet matchmakingRuleSet;

// Alarm that triggers when the per-second average of not placed matches exceed 10%
MathExpression ruleEvaluationRatio = MathExpression.Builder.create()
        .expression("1 - (ruleEvaluationsPassed / ruleEvaluationsFailed)")
        .usingMetrics(Map.of(
                "ruleEvaluationsPassed", matchmakingRuleSet.metricRuleEvaluationsPassed(MetricOptions.builder().statistic(Statistic.SUM).build()),
                "ruleEvaluationsFailed", matchmakingRuleSet.metric("ruleEvaluationsFailed")))
        .build();
Alarm.Builder.create(this, "Alarm")
        .metric(ruleEvaluationRatio)
        .threshold(0.1)
        .evaluationPeriods(3)
        .build();
```

C# / .NET:

```csharp
// Install: dotnet add package Amazon.CDK.Lib
MatchmakingRuleSet matchmakingRuleSet;

// Alarm that triggers when the per-second average of not placed matches exceed 10%
var ruleEvaluationRatio = new MathExpression(new MathExpressionProps {
    Expression = "1 - (ruleEvaluationsPassed / ruleEvaluationsFailed)",
    UsingMetrics = new Dictionary<string, IMetric> {
        { "ruleEvaluationsPassed", matchmakingRuleSet.MetricRuleEvaluationsPassed(new MetricOptions { Statistic = Statistic.SUM }) },
        { "ruleEvaluationsFailed", matchmakingRuleSet.Metric("ruleEvaluationsFailed") }
    }
});
new Alarm(this, "Alarm", new AlarmProps {
    Metric = ruleEvaluationRatio,
    Threshold = 0.1,
    EvaluationPeriods = 3
});
```

Golang:

```go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var matchmakingRuleSet MatchmakingRuleSet

// Alarm that triggers when the per-second average of not placed matches exceed 10%
ruleEvaluationRatio := cloudwatch.NewMathExpression(&MathExpressionProps{
	Expression: jsii.String("1 - (ruleEvaluationsPassed / ruleEvaluationsFailed)"),
	UsingMetrics: map[string]IMetric{
		"ruleEvaluationsPassed": matchmakingRuleSet.metricRuleEvaluationsPassed(&MetricOptions{
			"statistic": cloudwatch.Statistic_SUM,
		}),
		"ruleEvaluationsFailed": matchmakingRuleSet.metric(jsii.String("ruleEvaluationsFailed")),
	},
})
cloudwatch.NewAlarm(this, jsii.String("Alarm"), &AlarmProps{
	Metric: ruleEvaluationRatio,
	Threshold: jsii.Number(0.1),
	EvaluationPeriods: jsii.Number(3),
})
```

## Initializer

TypeScript:

```ts
new MathExpression(props: MathExpressionProps)
```

Python:

```python
MathExpression(props: MathExpressionProps)
```

Java:

```java
new MathExpression(MathExpressionProps props)
```

C# / .NET:

```csharp
new MathExpression(MathExpressionProps props)
```

Golang:

```go
NewMathExpression(Props MathExpressionProps)
```

## Properties

- `color`: string — The hex color code, prefixed with '#' (e.g. '#00ff00'), to use when this metric is rendered on a graph. The `Color` class has a set of standard colors that can be used here.

- `expression`: string — The expression defining the metric.

- `label`: string — Label for this metric when added to a Graph.

- `period`: [Duration](/cdk/api/v2/docs/aws-cdk-lib.Duration.html) — Aggregation period of this metric.

- `searchAccount`: string — Account to evaluate search expressions within.

- `searchRegion`: string — Region to evaluate search expressions within.

- `usingMetrics`: { [key: string]: [IMetric](/cdk/api/v2/docs/aws-cdk-lib.aws_cloudwatch.IMetric.html) } — The metrics used in the expression as KeyValuePair <id, metric>.

- `visible`: boolean — Whether this metric should be visible in dashboard graphs.

- `warnings`: string[] — - use warningsV2

- `warningsV2`: { [key: string]: string } — Warnings generated by this math expression.

## Methods

- `createAlarm(scope: Construct, id: string, props: CreateAlarmOptions): Alarm` — Make a new Alarm for this metric.

  Combines both properties that may adjust the metric (aggregation) as well
  as alarm properties.

- `toMetricConfig(): MetricConfig` — Inspect the details of the metric object.

- `toString(): string` — Returns a string representation of an object.

- `with(props: MathExpressionOptions): MathExpression // chainable` — Return a copy of Metric with properties changed.

  All properties except namespace and metricName can be changed.

  **Parameters**

  - `props` — The set of properties to change.
