如果指定字段存在,如何聚合字段

时间:2017-08-03 07:39:32

标签: elasticsearch elasticsearch-aggregation

我有这样的文件

    {
        "_index": "message_2017-08",
        "_type": "comment",
        "_id": "c000001",
        "_source": {
          "companies": {
            "58f99f99ba63d10006291b59": {
              "id": "58f99f99ba63d10006291b59",
              "sentiment": "58f8898273fabd33ee09d317"
            }
          },
          "sentiment": "58f8898273fabd33ee09d319",
          "purpose": "58f8898373fabd33ee09d31a"
        }
   },
   {
        "_index": "message_2017-08",
        "_type": "comment",
        "_id": "c000002",
        "_source": {
          "companies": {
            "58f99f99ba63d10006291b59": {
              "id": "58f99f99ba63d10006291b59"
            }
          },
          "sentiment": "58f8898273fabd33ee09d317",
          "purpose": "58f8898373fabd33ee09d31a"
        }
   },
   {
        "_index": "message_2017-08",
        "_type": "comment",
        "_id": "c000003",
        "_source": {
          "sentiment": "58f8898273fabd33ee09d318",
          "purpose": "58f8898373fabd33ee09d31a"
        }
   }

我想汇总文件,以防万一,

  • 如果_source.companies.{company_id}.sentiment现有使用此字段

  • 如果不使用_source.sentiment

我尝试像这样聚合,但收到有关null_pointer_exception

的错误
"aggs": {
  "by_sentiment": {
    "terms": {
      "script": {
        "inline": "if(params['_source']['companies']['58f99f99ba63d10006291b59']['sentiment'].empty == 'true'){return params['_source']['sentiment']} else {return params['_source']['companies']['58f99f99ba63d10006291b59']['sentiment']}"
      }
    }
  }
}
谁有任何想法?如何检查脚本中存在的字段?

1 个答案:

答案 0 :(得分:1)

我猜如果路径中的一个元素丢失,rebase将为null,因此调用isEmpty会抛出NPE。

在路径中的每个元素上调用isEmpty之前,请尝试检查是否为null。

相关问题