【问题标题】:How to get total score specific to each row如何获得特定于每一行的总分
【发布时间】:2015-07-07 15:17:43
【问题描述】:

我需要,Elasticsearch GET 查询通过将他们在所有科目中获得的分数相加来查看每个学生的总分,而不是我得到每个科目中所有学生的总分。

GET /testindex/testindex/_search
{
  "query" : {
    "filtered" : {
        "query" : { 
          "match_all" : {}
        }
    }
 },
 "aggs": {
    "total": {
        "sum": {
           "script" : "doc['physics'].value + doc['maths'].value + doc['chemistry'].value"
         }
     }
  }
}

输出

  {
    ....
   "hits": [
     {
        "_index": "testindex",
        "_type": "testindex",
        "_id": "1",
        "_score": 1,
        "_source": {
           "personalDetails": {
              "name": "viswa",
              "age": "33"
           },
           "marks": {
              "physics": 18,
              "maths": 5,
              "chemistry": 34
           },
           "remarks": [
              "hard working",
              "intelligent"
           ]
        }
     },
     {
        "_index": "testindex",
        "_type": "testindex",
        "_id": "2",
        "_score": 1,
        "_source": {
           "personalDetails": {
              "name": "bob",
              "age": "13"
           },
           "marks": {
              "physics": 48,
              "maths": 45,
              "chemistry": 44
           },
           "remarks": [
              "hard working",
              "intelligent"
           ]
        }
     }
  ]
  },
  "aggregations": {
     "total": {
        "value": 194
     }
  }
 }

预期输出:

我想得到每个学生的科目总分,而不是所有学生的总分。

我需要在查询中进行哪些更改才能实现此目的。

【问题讨论】:

  • 听起来你想要一个脚本字段而不是聚合

标签: elasticsearch


【解决方案1】:
{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      }
    }
  },
  "aggs": {
    "student": {
      "terms": {
        "field": "personalDetails.name",
        "size": 10
      },
      "aggs": {
        "total": {
          "sum": {
            "script": "doc['physics'].value + doc['maths'].value + doc['chemistry'].value"
          }
        }
      }
    }
  }
}

但是,请注意,对于 student terms 聚合,您需要一个“唯一”(使该学生独一无二的东西 - 例如个人 ID 或其他东西)字段,可能是 _id 本身,但您需要store它。

【讨论】:

  • 感谢您提供解决方案;我忘记了存储桶的概念,请问您是否使用任何工具来形成此查询?我正在使用漫威;如果你有任何这样的,请分享它。谢谢
  • 我的所有测试都使用Marvel's Sense dashboard
猜你喜欢
  • 1970-01-01
  • 2019-12-28
  • 1970-01-01
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
  • 2015-08-04
  • 2013-04-18
相关资源
最近更新 更多