You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch地理距离查询如何结合门店配送范围字段过滤记录

Elasticsearch 嵌套门店双重距离过滤实现方案

要实现你的过滤需求,只需要在原有nested查询的filter数组中新增painless脚本查询,完成「用户位置到门店的距离 ≤ 门店自身配送范围」的判断即可,具体实现如下:

核心逻辑

  • 保留原有geo_distance过滤,先筛选出在用户输入的搜索范围内的门店,减少后续脚本计算的数据量,提升查询性能
  • 新增script查询,通过ES内置的距离计算方法,比对实际距离和门店配置的配送距离

完整查询DSL

GET /product/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "title": "Product"
          }
        }
      ],
      "filter": [
        {
          "nested": {
            "path": "stores",
            "query": {
              "bool": {
                "filter": [
                  // 条件1:门店在用户输入的搜索范围内
                  {
                    "geo_distance": {
                      "distance": "50km", // 替换为用户输入的搜索距离
                      "stores.location.geoPoint": { 
                        "lat": 26.944535, // 用户当前纬度
                        "lon": 75.7747515 // 用户当前经度
                      }
                    }
                  },
                  // 条件2:用户位置在门店的配送范围内
                  {
                    "script": {
                      "params": {
                        "userLat": 26.944535,
                        "userLon": 75.7747515
                      },
                      "source": """
                        // 计算门店到用户的距离,转为千米单位
                        double distanceKm = doc['stores.location.geoPoint'].arcDistance(params.userLat, params.userLon) / 1000;
                        // 比对距离和门店配送范围
                        return distanceKm <= doc['stores.deliverableDistance'].value;
                      """
                    }
                  }
                ]
              }
            },
            "inner_hits": {}
          }
        }
      ]
    }
  }
}

验证说明

你给出的示例场景中,该查询会先筛选出50km内的所有门店,再通过脚本判断:

  • 门店1距离用户2Km ≤ 配送范围3Km,符合要求
  • 门店2距离用户10Km > 配送范围4Km,不符合要求
    最终仅门店1会出现在inner_hits返回结果中,完全匹配需求。

内容的提问来源于stack exchange,提问作者Ravi Soni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 16:30:05