Skip to content

Create



POST /api/v1/aggs_to_metric/add

Overview

Create a rule that periodically aggregates raw data and generates a new metric.

Before Calling and Usage Steps

First validate the raw data and q, then define a non-duplicate output metric+metricField, and provide jsonScript and extend in full. Explicitly specifying qtype=dql, qmode=selectorQuery, and fieldKey/funcName is recommended. In manual mode, explicitly specify customQuery; extend can be {}. New rules are enabled by default and can later be controlled with the enable/disable API.

For each workspace, the output metric+metricField is checked against all non-deleted aggs rules, including disabled rules. When a duplicate exists and skipRepeatNameCheck=false, nothing is saved or modified, yet the response is still HTTP 200 with success=true, while the top-level code=409, content.metricRepeat=true, and an English content.message are returned; you must check code and metricRepeat, and must not judge only by HTTP status or success. skipRepeatNameCheck=true skips only that check and does not prove that same-named outputs will not affect each other.

In selector mode, Distribution requires extend.funcName=distribution, and q uses histogram_auto(real numeric field). Field values, grouping, and filtering are actually determined by q; extend does not automatically rewrite q. unit only labels the display unit; numeric conversion must be explicitly handled in the query or on the collection side.

Saving configures the periodic schedule and synchronizes the metric unit/description. It does not synchronously execute the configured aggregation q or produce new metric data, but a create request may synchronously query the source field Schema to validate field types; when subsequent jobs run, whether they succeed, and whether the metric is written must be verified in job/metric queries. The scheduling service and the database/metric metadata are processed in separate steps, so an error or timeout may have already applied partial updates; read the rule and the target metric before retrying. This feature is not available to Free Plan workspaces.

Request Headers

Parameter Type Required Description
DF-API-KEY string Y OpenAPI authentication credential for the workspace.
Example: <DF-API-KEY>
How to obtain or fill in: Obtain an OpenAPI Key with this operation permission from API Key management in the target workspace.

Body Request Parameters

Parameter Type Required Description
jsonScript.query.q string Required string inside the query object. Selector mode must also provide the complete q; do not put credentials in it. The Distribution example uses histogram_auto(field), not distribution(field).
Example: L('default')::`nginx`:(count(`*`)) BY `host`
How to obtain or fill in: Build the aggregation query using actual DQL or PromQL syntax, with real log indexes, sources, and fields.
jsonScript.query.qtype string Optional query syntax; when omitted, dql is used by default. Only dql/promql may be specified explicitly; empty strings or null are not allowed. Always filling it in is recommended. PromQL executes as an instant query; rangeQuery is not set through this object.
Example: dql
How to obtain or fill in: Use dql for DQL and promql for PromQL.
jsonScript.query.qmode string Optional, specifying it explicitly is recommended. selectorQuery requires extend.fieldKey/funcName; customQuery does not have that echo-field requirement. When omitted, the controller does not trigger selector-mode structure validation, but the plugin may still validate functions as selector mode, so omission cannot be used to bypass validation.
Example: selectorQuery
How to obtain or fill in: Use selectorQuery for console selector mode and customQuery for manually written queries.
extend.funcName string Conditionally required aggregation function name for selectorQuery. count counts, count_distinct counts distinct values; numeric aggregation functions require a real numeric field; distribution echoes the corresponding histogram_auto in q.
Example: count
How to obtain or fill in: Choose count/avg/max/sum/min/count_distinct/distribution/p75/p95/p99.
extend.fieldKey string Conditionally required echo aggregation field for selectorQuery. On create, the source field type is queried to check compatibility with numeric functions, but unknown fields are not guaranteed to be rejected; update does not repeat the same field type check.
Example: *
How to obtain or fill in: Take the actual key from the raw data fields; for counting, * can be used as in q.
extend.source string Optional source echo; * indicates all available sources, and the actual scope is still limited by q. When querying the RUM list, this value can be used to attach sourceInfo.
Example: nginx
How to obtain or fill in: For logs take source, for APM take service, for RUM take app_id, for metrics take the measurement, for security take category, and for synthetic tests take the actual synthetic test data source.
extend.index string Optional log index echo; changing it does not automatically change the L index in q.
Example: default
How to obtain or fill in: Get it from the log index configuration of the current workspace; the default index is generally default.
extend.groupBy array Optional group-by echo array; when omitted, the echo field is absent; an empty array means no grouping. Actual grouping is determined by q.
Example: ["host"]
How to obtain or fill in: Choose the real fields from the BY grouping in q or the PromQL label aggregation.
extend.groupBy[*] string A single grouping key.
Example: host
How to obtain or fill in: Take the raw field name or tag name.
extend.filterString string Optional log filter echo string; it is not an automatic concatenation entry for q; actual filtering must be written into q.
Example: env:production
How to obtain or fill in: In log selector mode, you can copy the raw FilterString from the console filter.
extend.filters array Optional array; uses the plural values, unlike value in other APIs. Actual filter execution is determined by q.
Example: [{"name": "env", "condition": "and", "op": "=", "values": ["production"]}]
How to obtain or fill in: Filter echo used by non-log selectors.
extend.filters[*] json Filter echo object; the client's existing format can be preserved recursively; the current echo structure is not converted into an executed query.
Example: {"name": "env", "condition": "and", "op": "=", "values": ["production"]}
How to obtain or fill in: Keep one selector condition per item.
extend.filters[*].name string Echo field.
Example: env
How to obtain or fill in: Real source field name.
extend.filters[*].condition string Relationship with the previous echo condition.
Example: and
How to obtain or fill in: Use and/or; the display convention when omitted is and.
extend.filters[*].op string Echo operator; query condition conversion is not performed by this API.
Example: =
How to obtain or fill in: Use =, !=, match, or not match according to the client selector.
extend.filters[*].values array Echo value array; the actual comparison and value retrieval must both be reflected in q.
Example: ["production"]
How to obtain or fill in: Use raw field values and preserve the string/number/boolean type.
extend.filters[*].values[*] JSON A single string, numeric, or boolean value.
Example: production
How to obtain or fill in: Take a single field value from the source data.
extend json Y Required echo object; update replaces it entirely. None of the echo options replace jsonScript.query; when manual mode does not need echo, {} can be given.
Null allowed: False
Example: {"funcName": "count", "fieldKey": "*", "source": "nginx", "index": "default", "groupBy": ["host"], "filters": [], "filterString": ""}
How to obtain or fill in: Used for echo in the client editor; keep it consistent with the selections already written into q.
jsonScript json Y Required rule object; update replaces it entirely without field merging. Submit only the subfields listed on this page; do not send back the entire entity returned by the details API.
Null allowed: False
Example: {"type": "logToMetric", "query": {"q": "L('default')::`nginx`:(count(`*`)) BY `host`", "qtype": "dql", "qmode": "selectorQuery"}, "metricInfo": {"every": "5m", "metric": "recording_rules", "metricField": "nginx_requests"}}
How to obtain or fill in: Build it from the raw data category, query statement, and output metric definition; for update, first read the complete object from the details.
jsonScript.type string Y Required data category; the public declaration accepts only these six; an internal object plugin does not mean it is currently publicly supported by the OpenAPI. Update cannot change the category.
Null allowed: False
Empty string allowed: False
Allowed values: ['logToMetric', 'rumToMetric', 'apmToMetric', 'metricToMetric', 'securityToMetric', 'dialingToMetric']
Example: logToMetric
How to obtain or fill in: Logs use logToMetric, RUM uses rumToMetric, APM uses apmToMetric, metrics use metricToMetric, security uses securityToMetric, and synthetic tests use dialingToMetric.
jsonScript.query json Y Required query object; actual execution is determined by q, and the query is not automatically generated or corrected from extend fields. A successful save does not guarantee that the query syntax, data availability, or generated results meet expectations.
Null allowed: False
Example: {"q": "L('default')::`nginx`:(count(`*`)) BY `host`", "qtype": "dql", "qmode": "selectorQuery"}
How to obtain or fill in: First verify the real data, aggregation results, and grouping fields with the query tool in the same workspace.
jsonScript.metricInfo json Y Required output and scheduling object. Update backfills it entirely; metric/metricField cannot be changed; the unit and description can be changed, and omitting them synchronizes them as empty strings.
Null allowed: False
Example: {"every": "5m", "metric": "recording_rules", "metricField": "nginx_requests", "unit": "custom/[\"custom\",\"次\"]", "desc": "按host统计nginx请求数。", "delaySeconds": 60}
How to obtain or fill in: The business side defines the output metric; first check whether it is duplicated in existing generated metric rules.
jsonScript.metricInfo.every string Y Required frequency, with no leading zeros; 60m, 0m, seconds, days, or Cron expressions are not supported. It is used for the scheduling frequency and the query window length, not as the delay time.
Empty string allowed: False
Example: 5m
How to obtain or fill in: Choose 1m to 59m or 1h to 24h according to the generation frequency; m/h are lowercase.
jsonScript.metricInfo.metric string Y Required measurement name; only English letters, digits, and underscores; hyphens, spaces, or Chinese characters are not allowed. It cannot be changed on update.
Empty string allowed: False
Example: recording_rules
How to obtain or fill in: A custom output measurement name; confirm the name from Metrics Management or the generated metrics list.
jsonScript.metricInfo.metricField string Y Required metric name; the naming character restrictions are the same as metric. It cannot be changed on update; do not reuse 001-test from historical examples.
Empty string allowed: False
Example: nginx_requests
How to obtain or fill in: Define the output metric name under this measurement; check for the same metric+metricField in the rule list.
jsonScript.metricInfo.unit string Optional display unit string; omitted/empty string clears it; values in q are not automatically converted according to the unit, so you must ensure the query results match the unit yourself.
Empty string allowed: True
Example: custom/["custom","次"]
How to obtain or fill in: Refer to Unit Description; the standard format is custom/["time","ms"] and the custom format is custom/["custom","unit"].
jsonScript.metricInfo.desc string Optional metric description; omitted/empty string synchronizes it as empty; this is not the rule name.
Empty string allowed: True
Example: 按host统计nginx请求数。
How to obtain or fill in: Describe the output metric meaning, aggregation logic, and unit.
jsonScript.metricInfo.delaySeconds integer Optional wait in seconds; the default 0 means no delay. After a scheduled trigger, it waits for the source data to arrive; it does not change the query window corresponding to every, and if this field is not provided, an update resets it to 0. It must be a JSON integer; booleans or the string "60" are not accepted.
Allowed values: [0, 60, 120, 180, 300, 600, 900, 1200, 1800]
Example: 60
How to obtain or fill in: Choose only from 0/60/120/180/300/600/900/1200/1800.
skipRepeatNameCheck boolean Optional, default false; true skips the metric+metricField duplicate check against non-deleted generated rules in the same workspace. It does not mean the output data will not conflict, and it does not bypass naming/structure/scheduling validation.
Null allowed: False
Example: false
How to obtain or fill in: First check for the same output measurement + metric name via List Generated Metric Rules; usually false.

Additional Parameter Notes

For units, refer to Unit Description. The raw extend must stay consistent with the actual query; use every for the generation frequency and do not submit Cron expressions.

Request Example

curl --request POST 'https://openapi.guance.com/api/v1/aggs_to_metric/add' \
  -H 'DF-API-KEY: <DF-API-KEY>' \
  -H 'Content-Type: application/json' \
  --data-raw '{"jsonScript":{"type":"logToMetric","query":{"q":"L('"'"'default'"'"')::`nginx`:(count(`*`)) BY `host`","qtype":"dql","qmode":"selectorQuery"},"metricInfo":{"every":"5m","metric":"recording_rules","metricField":"nginx_requests","unit":"custom/[\"custom\",\"次\"]","desc":"按host统计nginx请求数。","delaySeconds":60}},"extend":{"funcName":"count","fieldKey":"*","source":"nginx","index":"default","groupBy":["host"],"filters":[],"filterString":""},"skipRepeatNameCheck":false}'

Response

HTTP 200 with the unified application/json envelope; a normal code=200 returns the rule, while duplicate output returns code=409 with success=true still, so content.metricRepeat must be checked.

Field Type Description
content.id integer or null Record ID; the create snapshot is generated before submission and may be null; operate using uuid.
content.uuid string rul_ rule UUID.
content.workspaceUUID string Owning workspace.
content.monitorUUID string Associated monitor UUID; usually an empty string in this module.
content.type string Entity type, fixed to aggs, distinct from jsonScript.type.
content.refKey string Reference key, usually empty.
content.secret string Entity compatibility field; usually empty for ordinary generated metric rules; do not use it as a calling credential or record actual values in it.
content.createdWay string manual/import/template, or an empty value from historical data.
content.isLocked integer or boolean Lock flag, usually 0/false.
content.openPermissionSet boolean Switch for custom operation permissions; usually false for records created by this module.
content.permissionSet array<string> Array of custom operation principals, usually [].
content.permissionSet[] string A single account/team/role identifier.
content.status integer 0 enabled, 2 disabled, 3 deleted; the status does not equal the success of the most recent job execution.
content.creator string Creating identity.
content.updator string Identity of the most recent update; may be empty initially.
content.createAt integer Creation Unix seconds.
content.updateAt integer Update Unix seconds; -1 if never updated.
content.deleteAt integer Deletion Unix seconds; -1 if not deleted.
content.crontabInfo object Scheduling configuration summary, not the job execution result.
content.crontabInfo.id string Scheduling configuration identifier, maintained by the system; use uuid to operate on the rule.
content.crontabInfo.crontab string The actual six-field scheduling expression, e.g. 0 */5 * * * *; the request frequency still uses metricInfo.every.
content.jsonScript object Saved configuration: Required rule object; update replaces it entirely without field merging. Submit only the subfields listed on this page; do not send back the entire entity returned by the details API.
content.jsonScript.type string Saved configuration: Required data category; the public declaration accepts only these six; an internal object plugin does not mean it is currently publicly supported by the OpenAPI. Update cannot change the category.
content.jsonScript.query json Saved configuration: Required query object; actual execution is determined by q, and the query is not automatically generated or corrected from extend fields. A successful save does not guarantee that the query syntax, data availability, or generated results meet expectations.
content.jsonScript.query.q string Saved configuration: Required string inside the query object. Selector mode must also provide the complete q; do not put credentials in it. The Distribution example uses histogram_auto(field), not distribution(field).
content.jsonScript.query.qtype string Saved configuration: Optional query syntax; when omitted, dql is used by default. Only dql/promql may be specified explicitly; empty strings or null are not allowed. Always filling it in is recommended. PromQL executes as an instant query; rangeQuery is not set through this object.
content.jsonScript.query.qmode string Saved configuration: Optional, specifying it explicitly is recommended. selectorQuery requires extend.fieldKey/funcName; customQuery does not have that echo-field requirement. When omitted, the controller does not trigger selector-mode structure validation, but the plugin may still validate functions as selector mode, so omission cannot be used to bypass validation.
content.jsonScript.metricInfo json Saved configuration: Required output and scheduling object. Update backfills it entirely; metric/metricField cannot be changed; the unit and description can be changed, and omitting them synchronizes them as empty strings.
content.jsonScript.metricInfo.every string Saved configuration: Required frequency, with no leading zeros; 60m, 0m, seconds, days, or Cron expressions are not supported. It is used for the scheduling frequency and the query window length, not as the delay time.
content.jsonScript.metricInfo.metric string Saved configuration: Required measurement name; only English letters, digits, and underscores; hyphens, spaces, or Chinese characters are not allowed. It cannot be changed on update.
content.jsonScript.metricInfo.metricField string Saved configuration: Required metric name; the naming character restrictions are the same as metric. It cannot be changed on update; do not reuse 001-test from historical examples.
content.jsonScript.metricInfo.unit string Saved configuration: Optional display unit string; omitted/empty string clears it; values in q are not automatically converted according to the unit, so you must ensure the query results match the unit yourself.
content.jsonScript.metricInfo.desc string Saved configuration: Optional metric description; omitted/empty string synchronizes it as empty; this is not the rule name.
content.jsonScript.metricInfo.delaySeconds integer Saved configuration: Optional wait in seconds; the default 0 means no delay. After a scheduled trigger, it waits for the source data to arrive; it does not change the query window corresponding to every, and if this field is not provided, an update resets it to 0. It must be a JSON integer; booleans or the string "60" are not accepted.
content.extend object Saved configuration: Required echo object; update replaces it entirely. None of the echo options replace jsonScript.query; when manual mode does not need echo, {} can be given.
content.extend.funcName string Saved configuration: Conditionally required aggregation function name for selectorQuery. count counts, count_distinct counts distinct values; numeric aggregation functions require a real numeric field; distribution echoes the corresponding histogram_auto in q.
content.extend.fieldKey string Saved configuration: Conditionally required echo aggregation field for selectorQuery. On create, the source field type is queried to check compatibility with numeric functions, but unknown fields are not guaranteed to be rejected; update does not repeat the same field type check.
content.extend.source string Saved configuration: Optional source echo; * indicates all available sources, and the actual scope is still limited by q. When querying the RUM list, this value can be used to attach sourceInfo.
content.extend.index string Saved configuration: Optional log index echo; changing it does not automatically change the L index in q.
content.extend.groupBy array Saved configuration: Optional group-by echo array; when omitted, the echo field is absent; an empty array means no grouping. Actual grouping is determined by q.
content.extend.groupBy[] string Saved configuration: A single grouping key.
content.extend.filterString string Saved configuration: Optional log filter echo string; it is not an automatic concatenation entry for q; actual filtering must be written into q.
content.extend.filters array Saved configuration: Optional array; uses the plural values, unlike value in other APIs. Actual filter execution is determined by q.
content.extend.filters[] json Saved configuration: Filter echo object; the client's existing format can be preserved recursively; the current echo structure is not converted into an executed query.
content.extend.filters[].name string Saved configuration: Echo field.
content.extend.filters[].condition string Saved configuration: Relationship with the previous echo condition.
content.extend.filters[].op string Saved configuration: Echo operator; query condition conversion is not performed by this API.
content.extend.filters[].values array Saved configuration: Echo value array; the actual comparison and value retrieval must both be reflected in q.
content.extend.filters[].values[] JSON Saved configuration: A single string, numeric, or boolean value.
content.__operation_info object Operation summary attached to a normal create response; not a request parameter, and not returned in the duplicate branch.
content.__operation_info.uuid string UUID of the rule created this time; identical to content.uuid.
content.declaration object or null Workspace common declaration attached to non-empty business objects; may be null or an empty object when not configured; empty objects are not added.
content.metricRepeat boolean Appears as true only in the duplicate branch, replacing the normal rule entity.
content.message string Hint that appears only in the duplicate branch; see the example for the English value.
code integer 200 on success; the duplicate branch returns 409 while HTTP remains 200 and success remains true.
content.retryable boolean May appear as true in content only for the 503 QueryServiceUnavailable error; it is not present in successful entities.
{
  "code": 200,
  "content": {
    "id": null,
    "uuid": "rul_aggs_example",
    "workspaceUUID": "wksp_example",
    "monitorUUID": "",
    "type": "aggs",
    "refKey": "",
    "secret": "",
    "jsonScript": {
      "type": "logToMetric",
      "query": {
        "q": "L('default')::`nginx`:(count(`*`)) BY `host`",
        "qtype": "dql",
        "qmode": "selectorQuery"
      },
      "metricInfo": {
        "every": "5m",
        "metric": "recording_rules",
        "metricField": "nginx_requests",
        "unit": "custom/[\"custom\",\"次\"]",
        "desc": "按host统计nginx请求数。",
        "delaySeconds": 60
      }
    },
    "extend": {
      "funcName": "count",
      "fieldKey": "*",
      "source": "nginx",
      "index": "default",
      "groupBy": [
        "host"
      ],
      "filters": [],
      "filterString": ""
    },
    "crontabInfo": {
      "id": "cron_example",
      "crontab": "0 */5 * * * *"
    },
    "createdWay": "manual",
    "isLocked": 0,
    "openPermissionSet": false,
    "permissionSet": [],
    "status": 0,
    "creator": "wsak_example",
    "updator": "",
    "createAt": 1785427200,
    "updateAt": -1,
    "deleteAt": -1,
    "declaration": {},
    "__operation_info": {
      "uuid": "rul_aggs_example"
    }
  },
  "errorCode": "",
  "message": "",
  "success": true,
  "traceId": "TRACE-EXAMPLE"
}

Duplicate output name, HTTP 200:

{
  "code": 409,
  "content": {
    "message": "Data duplication cannot be added",
    "metricRepeat": true,
    "declaration": {}
  },
  "errorCode": "",
  "message": "",
  "success": true,
  "traceId": "TRACE-EXAMPLE"
}

Error Response

For authentication, rate limiting, and common request errors, see Common Error Definitions.

HTTP Status errorCode Trigger Condition Message or Response Description Handling
406 ft.ParameterValidationFailed A request field is missing, or a field value violates the declared validation constraints Parameter parsing failed Check the parameter location, field name, type, and value.
400 ft.RequestJsonFormatError The request JSON syntax is invalid Request JSON format error Fix the JSON according to content.reason, line, and column.
400 ft.JsonFormatError The top-level JSON is not an object Format error in some json files Submit a JSON object as shown in the example.
403 ft.InvalidMetricsName The measurement or metric name does not match the alphanumeric-underscore format Metric names can contain only letters, digits, and underscores Fix metric/metricField; do not use the hyphens from historical examples.
400 ft.ParamsValidateError The query/metricInfo structure is invalid, jsonScript contains unknown fields, the frequency or delay value fails business validation, or selector mode is missing fieldKey/funcName Parameter validation failed: {} Check the field paths in the message; use only the allowed values on this page for frequency and delay, and explicitly provide qmode and qtype.
400 ft.OuterFuncFailed The scheduling service returned an explicit failure External function call failed Check existing rules and scheduling, then retry; if it keeps failing, provide the traceId.
400 ft.SameSetTraggerExists The scheduling service found an identical configuration A trigger with the same configuration already exists First check existing rules and jobs to avoid duplicate scheduling.
500 ft.InternalServerError Downstream timeout/ordinary 5xx, or database or subsequent metadata processing failure Internal error First read the rule and its status, the output metric, and the current scheduling state, then decide whether to retry; provide the traceId.
406 ft.UnsupportAggregateFunction On create, the plugin evaluates in selector mode that funcName is not in the supported set, including when qmode is omitted but extend is incomplete Unsupported aggregation function Explicitly fill in qmode and provide a valid funcName in selector mode.
406 ft.FieldTypeUnsupportFunc On create, the numeric aggregation field in selector mode is confirmed not to be a numeric type This field {} of type {} does not support this calculation function {} Choose a numeric field or a compatible aggregation function; update does not repeat the same check.
400 ft.FiledCreateTrigger The create schedule did not return a valid id Failed to create trigger configuration, please retry First check whether a rule/schedule already exists; if it keeps failing, provide the traceId.
503 ft.QueryServiceUnavailable The query service returns 503 when querying source field types on create, normalized to a retryable 503 with content.retryable=true The query service is temporarily unavailable, please try again later Retry with backoff; if it keeps failing, provide the traceId.
429 ft.KodoServerOverloaded Field queries on create are overloaded The current request rate is too high, please try again later. Retry with backoff and reduce concurrency.
403 ft.Forbidden The API Key has insufficient permissions, or the workspace plan does not support this feature You do not have permission for this operation Use an API Key with the corresponding permission and a workspace that supports generated metrics.

Feedback

Is this page helpful?