指标(PredItemType)

PredItemType 描述了一条返回列(指标或表达式),相当于 SQL SELECT 子句中的一项。其接口定义如下:

export interface PredItemType {
  operator?: string;
  pred?: string | PredItemType;
  name?: string;
  schema?: string;
  query?: QueryType;
  args?: { [key: string]: any };
  params?: any[];        // 兼容旧版参数定义
  type?: string;         // @deprecated
  by?: string;           // @deprecated
}

基本示例

{
  "name": "销售额",
  "operator": "$sum",
  "pred": "amount"
}

会被翻译为 SUM(amount) AS 销售额。其中:

  • name:结果中的列名;未设置时会自动生成。
  • operator:使用的算子(聚合、派生指标或自定义函数)。
  • pred:算子作用的字段,某些算子可嵌套新的 PredItemType
  • query:该指标独有的过滤条件,不影响其他指标。
  • schema:当指标需要跨模型引用其他 schema 时显式指定。
  • args:算子的函数参数,使用对象方式传递(而非 params 数组)。 目前没有太多算子使用此参数。但未来版本的Logicform预计会全面改为此参数。

常用算子

算子说明
$sum / $avg / $count常用聚合函数。$count 无需 pred
$distinct / $uniq统计去重后的数量,$uniq 针对用户 ID 等高并发场景做了优化。
$yoy / $mom / $sply / $splm自动计算同比、环比或上一周期数值,并补齐时间对齐逻辑。
$dailyavg / $monthlyavg将原始值按自然日 / 自然月平均,多用于平滑波动。
$sql执行自定义 SQL 片段。可通过 args/params 注入变量。
$piecewise将连续数值字段分段,常与用户画像等分桶场景配合使用。

如需自定义指标,可在语义层中声明算子名称,然后在 operator 中引用该名称。

算子参数(args)

当算子需要额外参数时,使用 args 对象传递(推荐使用 args 而非 params):

{
  "preds": [
    {
      "name": "移动平均销售额",
      "operator": "$moving_avg",
      "pred": "amount",
      "args": {
        "window": 7,
        "center": true
      }
    }
  ]
}

常用算子参数示例:

算子可用参数说明
$moving_avgwindow, center移动平均窗口大小和是否居中
$percentilepercentile百分位数计算,如 0.5 表示中位数
$sqlsql, bindings自定义 SQL 片段及变量绑定
$piecewisecases分段规则配置

指标级别筛选

同时计算“今年销售额”和“去年销售额”时,可以把时间条件写在各自的 query 字段中:

{
  "schema": "sales",
  "preds": [
    {
      "name": "去年销售额",
      "operator": "$sum",
      "pred": "amount",
      "query": { "日期": { "year": 2023 } }
    },
    {
      "name": "今年销售额",
      "operator": "$sum",
      "pred": "amount",
      "query": { "日期": { "year": 2024 } }
    }
  ]
}

分段算子($piecewise)

当用户提问“不同年龄段的客户数量”时,系统会自动将数值字段进行分段。生成的 Logicform 结构示例:

{
  "groupby": [
    {
      "_id": "年龄",
      "operator": "$piecewise",
      "name": "年龄段"
    }
  ],
  "preds": [{ "operator": "$count", "name": "用户数" }]
}

在语义层的专家模式中可以预先配置分段逻辑:

{
  "cases": [
    { "when": "age < 30", "then": "0-29" },
    { "when": "age >= 30 AND age < 50", "then": "30-49" },
    { "else": "50+" }
  ]
}

系统会将上述配置转译为 SQL CASE WHEN,并保证同一分段在不同看板中保持一致。

更多算子约定可在语义层中查看,也可以通过插件扩展新的 operator。编写指标时请始终命名 name,确保 sorthaving 等语义能够准确引用。

跨 Schema 引用

当需要引用其他模型(schema)的字段时,使用 schema 字段显式指定:

{
  "schema": "orders",
  "preds": [
    {
      "name": "订单销售额",
      "operator": "$sum",
      "pred": "amount"
    },
    {
      "name": "关联客户数",
      "operator": "$count",
      "pred": "id",
      "schema": "customers"
    }
  ]
}

系统会自动处理跨模型的关联逻辑,确保指标能够正确计算。当主 schema 和 pred 的 schema 不同时,执行引擎会根据语义层配置自动生成 JOIN。