通过 script_score 调用 xgboost 模型打分

解读

国内中大型公司在做“搜索+推荐”混合排序时,往往先用 Elasticsearch(ES)召回千级候选,再用 XGBoost 模型 精排。ES 7.6+ 官方支持在 script_score 查询里加载并调用 本地或共享存储的 XGBoost 模型,实现“在倒排召回阶段就完成机器学习打分”,既节省一次 RPC,又能利用 ES 的分布式并行能力。
面试高频点集中在:

  1. 模型如何注册到 ES 集群;
  2. script_score 里如何拿到特征向量;
  3. 打分脚本性能调优与版本兼容性;
  4. 线上灰度、热更新与回滚方案。
    答不出“模型缓存、分片级线程安全、特征缺失兜底”三点,基本会被判为“只看过博客”。

知识点

  1. XGBoost 模型格式:必须导出为 JSON(原生 xgb 二进制无法直接加载),且只支持 回归树(gbtree),不支持线性 booster 和多分类。
  2. 模型注册 API:
    • 7.x 用 _ml/trained_models/{model_id} 接口上传,存储在 .ml-state 索引;
    • 8.x 统一归到 _ml/trained_models,且强制要求 feature_importance 元数据。
  3. script_score 上下文:
    • 只能访问 doc values(禁用 _source),因此所有特征字段必须 doc_values:true;
    • 返回 float,异常值会被 ES 置为 0,需自行 Math.max(0, score) 兜底。
  4. 推理函数:
    • 7.6-7.9 使用 xgboost(model_id, features);
    • 7.10+ 推荐 ml.infer(model_id, {'feature_vector':[...]}),支持 批量推理 与 缓存复用。
  5. 性能红线:
    • 单分片单次查询 模型推理耗时 < 5 ms,否则 GC 抖动会拖垮搜索线程池;
    • 特征维度 ≤ 200,树深度 ≤ 8,叶子节点 ≤ 1024,否则 HotThreads 采样会看到 XGBoostNativeImpl 占满 CPU。
  6. 安全与回滚:
    • 模型文件先传到 共享仓库(HDFS/NFS),通过 ML Node 角色节点加载,避免 Data Node OOM;
    • 使用 alias + filter 做灰度,回滚时切换别名即可;
    • 开启 xpack.ml.max_inference_threads: 2,防止 推理线程池 打满。

答案

实操步骤(以 ES 7.17 集群、三节点 ML 角色为例):

  1. 训练并导出模型
    Python 端用 xgboost 1.5,训练后执行

    bst.save_model('model.json')
    xgb.to_json(bst, 'model.json')  # 确保是 JSON 格式
    
  2. 创建特征字段映射

    PUT my_index
    {
      "mappings": {
        "properties": {
          "price": {"type": "half_float", "doc_values": true},
          "brand_id": {"type": "keyword", "doc_values": true},
          "ctr_7d": {"type": "float", "doc_values": true}
        }
      }
    }
    
  3. 上传模型到集群

    PUT _ml/trained_models/product_rank_xgb
    {
      "description": "xgb regression for search ranking",
      "input": {"field_names": ["price", "brand_id", "ctr_7d"]},
      "definition": {
        "preprocessors": [
          {"one_hot_encoding": {"field": "brand_id", "hot_map": {"apple":0, "huawei":1}}}
        ],
        "trained_model": {
          "ensemble": {
            "feature_names": ["price", "brand_id=apple", "brand_id=huawei", "ctr_7d"],
            "tree": { ... }  // 这里粘贴 model.json 的 tree 字段
          }
        }
      }
    }
    
  4. script_score 查询调用

    GET my_index/_search
    {
      "query": {
        "script_score": {
          "query": {"bool": {"filter": {"term": {"status": 1}}}},
          "script": {
            "source": """
              // 构造特征向量,注意顺序与 model 一致
              double[] vec = new double[4];
              vec[0] = doc['price'].value;
              if (doc['brand_id'].value == 'apple') { vec[1] = 1; } else { vec[1] = 0; }
              if (doc['brand_id'].value == 'huawei') { vec[2] = 1; } else { vec[2] = 0; }
              vec[3] = doc['ctr_7d'].value;
              // 调用模型并兜底
              float score = ml.infer('product_rank_xgb', {'feature_vector': vec});
              return Math.max(0.0, score);
            """,
            "lang": "painless"
          }
        }
      },
      "size": 100
    }
    
  5. 性能调优

    • 在 elasticsearch.yml 加
      xpack.ml.max_inference_threads: 4
      xpack.ml.model_repository: /mnt/shared_models
      
    • 使用 preference=_local 减少 跨节点拉取模型;
    • 对 冷索引 先 forcemerge 到 1 段,降低 doc values 随机 IO。
  6. 灰度与回滚
    创建索引别名 my_index_v1,新模型上线时 reindex 到 my_index_v2,别名切换即可 0 downtime。

拓展思考

  1. 特征实时性:
    如果 ctr_7d 需要 Flink 实时更新,可把特征写到 Redis,再在脚本里用 painless 的 redis client 扩展(需自己写 ScriptEngine 插件),但官方建议 把实时特征预写回 ES 用 update_by_query,避免 搜索线程 被 网络 IO 堵住。
  2. 多模型融合:
    ES 8.2+ 支持 inference processor 在 ingest pipeline 里 一次性跑多个模型,把结果写回 rank_score 字段,后续 script_score 直接读字段即可,推理与搜索线程完全解耦。
  3. A/B 实验:
    利用 search template + preference=_primary_first 让 10% 流量 走新模型,90% 流量 走旧模型,通过 kibana lens 对比 CTR/GMV;回滚时只需 删除模板 即可。