首页 > 解决方案 > Elasticsearch 包括每个嵌套对象的 geo_distance 并按 [0] element.distance 排序

问题描述

我有以下映射:

properties: {
                locations: {
                    type: 'nested',
                    properties: {
                        location: {
                            type: 'geo_point'
                        }
                    }
                }
            }

并使用此查询过滤文档

body: {
  query: {
    bool: {
      must: [{
        nested: {
          path: 'locations',
          query: {
            bool: {
              filter: {
                geo_distance: {
                  distance: '300km',
                  'locations.location': {
                    lat: 32.77918970616056,
                    lon: -96.79523206899606
                  }
                }
              }
            }
          },
          inner_hits: {} //inner_hits here is for returning matched array elements
        }
      }]
    }
  }
}

这是我插入索引的文档示例:

{
  id: 5,
  name: 'My favorite name',
  locations: [{
      location: {
        lat: 35.57798637393296,
        lon: -97.33606463928675
      }
    },
    {
      location: {
        lat: 32.78743712185017,
        lon: -96.80344505382367
      }
    }
  ],
}

而且我寻找一种将计算出的距离包含到 inner_hits (或只是位置,这无关紧要)的能力。从这个答案中,我发现为了将字段附加到结果中,我可以在inner_hits属性中指定脚本,例如

inner_hits: {
  script_fields: {
    distance: {
      script: "1" //inner_hits will have distance property = 1
    }
  }
}

但我不明白如何访问 location 属性并调用.distanceInKm(32.77918970616056, -96.79523206899606). 此外,这种方法似乎从 inner_hits 中删除了所有其他属性,只剩下“距离”属性。我还需要保存原始属性。稍后使用 [0] 元素的计算距离对结果集进行排序。

标签: elasticsearchnesteddistance

解决方案


推荐阅读