将 DEM 高程存入 rank_feature 实现坡度排序

解读

国内 GIS、物流、出行类公司面试时,经常把“高程→坡度→排序”作为空间索引+评分函数的综合考点。
核心诉求是:

  1. 把**数字高程模型(DEM)**的每个像素高程值写进 Elasticsearch;
  2. 用rank_feature字段保存“可排序的数值特征”;
  3. 查询时不取回全部文档,仅靠内置函数就能按“坡度”降序排列,且支持秒级响应+水平分片。

知识点

  1. rank_feature 的本质
    单值浮点字段,只存正数,不参与 _source,倒排压缩存储,查询阶段用函数 score = sat1 * sat2 * … 直接乘到 _score,避免脚本排序的内存爆炸。
  2. 坡度公式
    坡度百分比 = Δh / L × 100%,其中 Δh 为高程差,L 为水平距离;面试时必须说明“L 取 8-邻域最短距离 90 m(假设 30 m 分辨率)”,否则会被追问“为什么不是欧式距离”。
  3. mapping 设计
    需同时存“高程 elevation(float)”与“坡度 slope(rank_feature)”两个字段;slope 值必须在索引期算好,因为 rank_feature 不支持脚本运行时生成。
  4. 写入流程
    用 Logstash 或 Spark 读取 GeoTIFF → 按瓦片编号生成 doc_id → 计算 slope → bulk 写入;必须设置 "slope": { "type": "rank_feature", "positive_score_impact": true },否则排序方向反了。
  5. 查询 DSL
    使用 rank_feature query 并指定 log1p 或 saturating 函数,function_score 里只能有一个 rank_feature 子句,否则乘法饱和;面试时要能手写:
    "query": {
      "rank_feature": {
        "field": "slope",
        "log": { "scaling_factor": 1 }
      }
    }
    
  6. 性能陷阱
    • 若把 slope 设成 short 类型再脚本排序,会导致 Fielddata 堆内存暴涨,GC 停顿;
    • 若用 geo_distance + 脚本排序,无法利用分片级短路,查询耗时随文档数线性增长;
    • rank_feature 字段不可聚合,如需同时统计“平均坡度”,需再存一个 slope_agg(float) 字段。

答案

步骤一:创建索引

PUT dem
{
  "mappings": {
    "properties": {
      "location": { "type": "geo_point" },
      "elevation": { "type": "float" },
      "slope": { "type": "rank_feature", "positive_score_impact": true }
    }
  }
}

步骤二:离线计算坡度
用 GDAL 读取 DEM,3×3 窗口计算最大高程差,坡度 = maxΔh / 90 × 100,保留 2 位小数;生成 ND-JSON:

{"index":{"_id":"x_y"}}
{"location":{"lat":30.1,"lon":120.2},"elevation":45.6,"slope":12.34}

步骤三:bulk 写入

curl -s -H "Content-Type: application/x-ndjson" -XPOST localhost:9200/_bulk --data-binary @dem.ndjson

步骤四:查询最陡的 10 个像素

GET dem/_search
{
  "size": 10,
  "query": {
    "rank_feature": {
      "field": "slope",
      "log": { "scaling_factor": 1 }
    }
  },
  "_source": ["location", "elevation", "slope"]
}

返回结果已按 坡度降序 排列,_score 越大越陡,单分片 1 亿文档 P99 < 50 ms。

拓展思考

  1. 实时坡度更新
    若 DEM 源为激光雷达持续入库,可用 Transform 持续聚合 3×3 窗口,输出到新的 slope 索引,实现近实时(5 s 延迟)坡度排序。
  2. 多因子排序
    业务需要“坡度大且距离用户近”,可在 function_score 里把 rank_feature(slope) 与 geo_distance 做 加权几何平均,注意 scaling_factor 统一量纲。
  3. 联邦查询
    省厅要求“跨集群比对历史年度坡度变化”,可用 CCR(跨集群复制) 把只读索引复制到分析集群,查询端用 rank_feature + alias 实现零停机比对。