【问题标题】:Elasticsearch range with aggs带有 aggs 的 Elasticsearch 范围
【发布时间】:2017-09-14 18:58:06
【问题描述】:

我想要每个用户文档的平均评分,但根据我的说法不起作用。请检查下面给出的代码。

 curl -XGET 'localhost:9200/mentorz/users/_search?pretty' -H 'Content-Type: application/json' -d' 
  {"aggs" : {"avg_rating" : {"range" : {"field" : "rating","ranges" : [{ "from" : 3, "to" : 19 }]}}}}';

{“_index”:“mentorz”,“_type”:“用户”,“_id”:“555”,“_source”:{“name”:“neeru”,“user_id”:555,“email_id” :“abc@gmail.com”,“关注者”:0, “以下”:0,“导师”:0,“受指导者”:0,“basic_info”:“api测试信息”, “birth_date”:1448451985397,“charge_price”:0,“org”:“cz”,“located_in”:“noida”,“position”:“sw developer”,“exp”:7,“video_bio_lres”:“test bio lres url normal signup","video_bio_hres" : "test bio hres url normal signup", "rating" : [ 5 ,4], "expertises" : [ 1, 4, 61, 62, 63 ] } 这是我的用户文档,我只想过滤平均评分范围为 3 到 5 的用户。

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    更新答案

    我已经使用脚本进行了查询,希望以下查询对您有用。

    GET mentorz/users/_search
    {
      "size": 0,
      "aggs": {
        "term": {
          "terms": {
            "field": "user.keyword",
            "size": 100
          },
          "aggs": {
            "NAME": {
              "terms": {
                "field": "rating",
                "size": 10,
                "script": {
                  "inline": "float var=0;float count=0;for(int i = 0; i < params['_source']['rating'].size();i++){var=var+params['_source']['rating'][i];count++;} float avg = var/count; if(avg>=4 && avg<=5) {avg}else{null}"
                }
              }
            }
          }
        }
      }
    }
    

    您可以通过更改 if 条件“if(avg>=4 && avg”来更改所需评分范围的范围。

    【讨论】:

    • 例如,如果用户的评分为 3,4,3,5。那么您是否想首先找到所有评分的平均值,即 (3+4+3+5)/4 = 3.75。然后,如果在这种情况下为 3.75 的平均评分介于 3 到 5 之间,则您需要过滤该用户文档。这就是你想要的吗?
    猜你喜欢
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 2019-03-18
    • 2018-11-28
    • 1970-01-01
    相关资源
    最近更新 更多