如何在Mixpanel JQL中计算各API调用量占总调用量的百分比
Mixpanel JQL实现API调用次数占比统计方案
你要的百分比统计完全可以实现,核心是先算出所有成功API调用的总次数,再逐个计算每个API的调用占比。修改后的代码如下:
function main() { // 过滤并分组统计每个API的成功调用次数 const apiCounts = Events({ from_date: '2024-08-01', to_date: '2024-08-15' }) .filter(function(event) { return event.name === "api_response" && event.properties.api_response_type === "success"; }) .groupBy(['properties.api_endpoint'], mixpanel.reducer.count()) .map(function(item) { return { "API Name": item.key[0], "Counts": item.value }; }) .toArray(); // 将分组结果转为数组,方便后续计算 // 计算所有API的总调用次数 const totalCalls = apiCounts.reduce(function(total, item) { return total + item.Counts; }, 0); // 遍历每个API项,计算百分比并格式化 return apiCounts.map(function(item) { const percentage = ((item.Counts / totalCalls) * 100).toFixed(2) + '%'; return { "API Name": item["API Name"], "Counts": item.Counts, "Percentage": percentage }; }); }
关键说明:
- 用
.toArray()将分组结果转为数组,才能通过reduce方法累加总调用次数 reduce方法遍历数组,从0开始累加所有API的调用次数,得到总次数- 百分比计算时用
toFixed(2)保留两位小数,再拼接百分号,确保格式符合需求
执行后会返回你期望的三列表格结果:
| API Name | Counts | Percentage |
|---|---|---|
| api_name_01 | 8 | 20.51% |
| api_name_02 | 13 | 33.33% |
| api_name_03 | 3 | 7.69% |
| api_name_04 | 9 | 23.07% |
| api_name_05 | 6 | 15.38% |
内容的提问来源于stack exchange,提问作者Amin
相关产品推荐
相关产品推荐

