elasticsearch - 如果指定字段存在,如何汇总字段

标签 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']}"
          }
        }
      }
    }
    

    有人有什么主意吗?如何检查脚本中存在的字段?

    最佳答案

    我猜如果路径中的元素之一丢失,params['_source']['companies']['58f99f99ba63d10006291b59']['sentiment']将为null,因此调用isEmpty会引发NPE。

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

    关于elasticsearch - 如果指定字段存在,如何汇总字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45477817/

    相关文章:

    elasticsearch - 我可以查询具有不同结构的两个不同索引并在Elasticsearch中合并结果吗?

    hadoop - 从存储在 HDFS 中的文档中提取数据以在 Elasticsearch 中建立索引

    elasticsearch - NEST ElasticSearch,查询结果为空

    elasticsearch - 如何在弹性聚合中检索时间戳以及最小值

    elasticsearch - 使用Elastic Search的自定义构面

    elasticsearch - Elasticsearch中对应的SQL聚合查询

    elasticsearch - 通过用户崩溃来计算百分位数

    elasticsearch - Elasticsearch :通过标签相似度获取相关内容

    elasticsearch - 在 Elasticsearch 中更改集群名称

    python - 如何使用elasticsearch生成词云?