使用“Profile”与“Monitoring History”定位一条 10 秒慢查询

解读

在国内金融、政务类 MarkLogic 项目中,10 秒级查询往往直接触发 SLA 告警,面试官想确认候选人是否能在生产环境无重启、无代码侵入的前提下,3 分钟内从“现象”到“根因”闭环。核心考点:

  1. 能否把**Profile(单次请求级)与Monitoring History(集群级时序)**两条线索交叉验证;
  2. 是否熟悉中文操作系统下常见“时间戳 8 小时时差”陷阱;
  3. 是否具备“先看资源、再看计划、最后看代码”的排查节奏,避免一上来就翻源码。

知识点

  1. Monitoring History
    属于系统性能采样表(Meters 与 Request-Detail),默认 60 s 聚合,retention 7 天。关键字段:

    • request-id:全局唯一,贯穿 Profile 与日志;
    • elapsed-time:单位 xs:duration,可直接 >PT10S 过滤;
    • statement-type:区分 XQuery、SQL、SPARQL、Optic;
    • forest-name、host-name:定位热点分片。
  2. Profile
    开启方式:

    • 单条调试:prof:enable(xdmp:request());
    • 集群级采样:group → profiler → enabled=true,采样率默认 1%,国内高并发场景建议提到 5% 避免漏采。
      输出格式:XML 树形片段,根节点 prof:profile,热点按 prof:time 降序,时间单位毫秒。
  3. 索引缺失特征
    在 Profile 中表现为 prof:expression 出现大量 prof:fragment-count=“N” 且 prof:lookup=“false”,同时 prof:filter-time 占比 >60%。

  4. 锁等待特征
    prof:lock-wait-time 连续大于 0,且 prof:forest-name 集中在同一森林,即可判定写热点锁。

  5. 时区修正
    国内服务器常用 CST(UTC+8),而 Monitoring History 存 UTC,where elapsed-time > PT10S and start-time > xs:dateTime('2024-05-28T08:00:00+08:00') 需先转 UTC 再比对。

答案

步骤一:用 Monitoring History 秒级锁定慢查询
在 Query Console 执行:

import module namespace mh = "http://marklogic.com/manage/monitoring" 
        at "/MarkLogic/manage/monitoring/monitoring-history.xqy";

for $r in mh:request-detail(
        xs:dateTime('2024-05-28T01:00:00Z'),  (: 前一小时 UTC :)
        xs:dateTime('2024-05-28T03:00:00Z'))
where $r/elapsed-time > xs:dayTimeDuration('PT10S')
  and $r/statement-type = 'xquery'
return
  <slow>
    <req-id>{ $r/request-id }</req-id>
    <host>{ $r/host-name }</host>
    <forest>{ $r/forest-name }</forest>
    <elapsed>{ $r/elapsed-time }</elapsed>
  </slow>

拿到request-id=123456789,确认host=ml-node-3。

步骤二:在同一节点提取 Profile
SSH 到 ml-node-3,用 curl 本地调用避免网络开销:

curl --anyauth -u admin:****** \
  -X GET -H "Accept: application/xml" \
  'http://localhost:8002/manage/v3/databases/my-db/profiling/123456789' \
  -o /tmp/123456789.xml

步骤三:读 Profile 定位瓶颈
打开 XML,发现:

  • prof:expression[@count=“480000”][@lookup=“false”]
  • prof:filter-time=8923 ms
  • prof:lock-wait-time=0 ms
    结论:索引缺失导致全片扫描,需对路径 /t:trade/t:counterparty-id 建元素范围索引。

步骤四:验证并闭环

admin:save-configuration(
  admin:database-add-range-element-index(
    admin:get-configuration(),
    xdmp:database("my-db"),
    xs:QName("counterparty-id"),
    "string"))

重建后复跑同一查询,Monitoring History 显示耗时降至 380 ms,告警解除。

拓展思考

  1. 若 Profile 中 prof:lock-wait-time 占大头,应优先检查森林级写队列与事务隔离级别(尤其是政府多部门并发写主数据场景)。
  2. 国内等保要求审计日志留存 6 个月,可把 Monitoring History 数据通过CORB批量抽到冷备集群,用 Optic 做月度慢 SQL 报告,实现“事后追责”。
  3. 对于混合事务+分析场景,可借助**“Query Isolation”与“Tiered Storage”把 10 秒级分析查询路由到只读副本**,避免影响核心交易。