elasticsearch Elasticsearch无法使用lang groovy运行内联脚本[doc…],elasticsearch,groovy,elasticsearch,Groovy" /> elasticsearch Elasticsearch无法使用lang groovy运行内联脚本[doc…],elasticsearch,groovy,elasticsearch,Groovy" />

elasticsearch Elasticsearch无法使用lang groovy运行内联脚本[doc…]

elasticsearch Elasticsearch无法使用lang groovy运行内联脚本[doc…],elasticsearch,groovy,elasticsearch,Groovy,当我尝试匹配索引中的所有内容并显示给定地理点与查询结果之间的距离时,出现此错误,我使用脚本的答案来显示距离: 这是我的DSL查询: { "query": { "match_all": {} }, "script_fields": { "distance": { "lang": "groovy", "params": { "lat": 2.27, "lon": 50.3 }, "script

当我尝试匹配索引中的所有内容并显示给定地理点与查询结果之间的距离时,出现此错误,我使用脚本的答案来显示距离:

这是我的DSL查询:

{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "distance": {
      "lang": "groovy",
      "params": {
        "lat": 2.27,
        "lon": 50.3
      },
      "script": "doc['geo_coordinates'].distanceInKm(lat,lon)"
    }
  }
}
查询响应:

{
  "took": 50,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 4,
    "failed": 1,
    "failures": [
      {
        "shard": 0,
        "index": "users",
        "node": "pa76fjdWQl2YAHmgCT4oKw",
        "reason": {
          "type": "script_exception",
          "reason": "failed to run inline script [doc['geo_coordinates'].distanceInKm(lat,lon)] using lang [groovy]",
          "caused_by": {
            "type": "null_pointer_exception",
            "reason": null
          }
        }
      }
    ]
  },
  "hits": {
    "total": 184,
    "max_score": 1,
    "hits": []
  }
在我的映射中有这样一个:

  "geo_coordinates" : {
            "type" : "geo_point",
            "lat_lon" : true
          },

所以我不明白为什么我会得到一个空指针

这可能是因为其中一个文档在geo_坐标字段中没有任何值。因此,您需要在脚本中说明这种情况

请尝试以下方法:

{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "distance": {
      "lang": "groovy",
      "params": {
        "lat": 2.27,
        "lon": 50.3
      },
      "script": "doc['geo_coordinates'] ? doc['geo_coordinates'].distanceInKm(lat,lon) : 0"
    }
  }
}

这可能是因为其中一个文档在geo_坐标字段中没有任何值。因此,您需要在脚本中说明这种情况

请尝试以下方法:

{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "distance": {
      "lang": "groovy",
      "params": {
        "lat": 2.27,
        "lon": 50.3
      },
      "script": "doc['geo_coordinates'] ? doc['geo_coordinates'].distanceInKm(lat,lon) : 0"
    }
  }
}

你的一个文档可能没有geo_坐标字段吗?不可能它确实存在于我的Mongodb和Elasticsearch mapping中。我不是说映射,但是如果你只有一个文档实例,这个字段没有任何值,这可能会解释NPE。是的,一些用户有这个字段,但没有任何值!好了,那么你应该修改你的脚本,只调用distanceInKm(如果该值存在)。你的一个文档是否可能没有地理坐标字段?不可能它确实存在于我的Mongodb和Elasticsearch mapping中我不是说映射,但是,如果您只有一个文档实例,但该字段没有任何值,那么这可能解释了NPE。是的,有些用户的该字段没有任何值!接下来,您应该修改脚本,使其仅在值存在时调用distanceInKm。doc['geo_coordinates']?。distanceInKmlat,lon?:0也应该可以工作。这是实现相同目标的一种较短的常规方法。doc['geo_coordinates']?。distanceInKmlat,lon?:0也应该可以工作,这是实现同样目标的一种较短的常规方法。