Elasticsearch无痛排序null_pointer_error

k4ymrczo  于 2022-12-22  发布在  ElasticSearch
关注(0)|答案(1)|浏览(145)

我正在尝试创建一个可以轻松过滤嵌套文档的排序脚本。我使用脚本来做这件事的原因是因为我需要模拟COALESCE语句。
我的文档的标题存储如下:

{
  title: [
    {
      type: MainTitle,
      value: [
        {
          language: eng,
          label: The title 
        },
        {
          language: ger,
          label: Das title 
        }
      ]
    },
    {
      type: AvailabilityTitle,
      value: [
        {
          language: eng,
          label: New thing! 
        }
      ]
    }
  ]
}

title和title.value是嵌套文档。
我想主要按英语主标题和德文主标题对文档进行排序 * 只有在 * 没有英文主标题的情况下-即使德文标题给了更高的分数。
我试图简单地排序的英语标题第一次尝试它,这是脚本:

def source = params._source;

def titles = source.title;
if (titles != null && titles.length > 0) {
    for(int i=0; i < titles.length; i++) {
        def t = titles[i];
        if (t.type == 'MainTitle') {
          
          def values = t.value;
          if (values != null && values.length > 0) {
            for (int j = 0; j < values.length; j++) {
              def v = values[j];
              if (v.language == 'eng') {

                return v.label;

              }
            }
          }
        
        }
    }
}

return \"\";

由于某种原因,我收到了null_pointer_exception

"script_stack": [
  "if (values != null && values.length > 0) {       ",
  "                            ^---- HERE"
],

我不明白值在那个点上怎么会是空的,因为我专门检查了它前面的空值。

k4emjkb1

k4emjkb11#

抛出null_pointer_exception,不是因为values为null,而是因为values没有名为length的方法/函数。这是因为 * 由于某种原因 * values是一个ArrayList,尽管titles之前是一个Array。显然,它们都有size()的方法/函数,所以我可以使用它。
这是可行的:

def source = params._source;

def titles = source.title;
if (titles != null && titles.size() > 0) {
    for(int i=0; i < titles.size(); i++) {
        def t = titles[i];
        if (t.type == 'MainTitle') {
          
          def values = t.value;
          if (values != null && values.size() > 0) {
            for (int j = 0; j < values.size(); j++) {
              def v = values[j];
              if (v != null && v.language == 'fin') {

                return v.label;

              }
            }
          }
        
        }
    }
}

return '';

相关问题