Elasticsearch 嵌套聚合与范围聚合

Elasticsearch nested aggregation with range aggregation

I am very new to ElasticSearch and trying to figure out a situation where I have to show particular JSON data from Elasticsearch. Please see below code

def bucket_for_order_amount(buckets, aggregations)
        buckets['order_range'] = {
          range: {
            field: :total,
            keyed: true, 
            ranges: [
                { to: 25.0 },
                { from: 25.0, to: 50.0 },
                { from: 50.0, to: 75.0 },
                { from: 75.0, to: 100.0 },
                { from: 100.0 }
            ]
          }
        }     
      end

这将 return JON 响应:

"report": {
        "order_range": {
            "buckets": {
                "*-25.0": {
                    "to": 25,
                    "doc_count": 0
                },
                "25.0-50.0": {
                    "from": 25,
                    "to": 50,
                    "doc_count": 0
                },
                "50.0-75.0": {
                    "from": 50,
                    "to": 75,
                    "doc_count": 0
                },
                "75.0-100.0": {
                    "from": 75,
                    "to": 100,
                    "doc_count": 0
                },
                "100.0-*": {
                    "from": 100,
                    "doc_count": 2
                }
            }
        }

I have a situation where I have to show the users listing inside the doc_count if any user exists in that range but I am not sure which aggregation need to use to achieve this response.

The response would be like this:-

"*-25.0": {
              "to": 25,
              "doc_count": 2
                         {
                     user1,
                     user2
               },
},

您可以使用 top_hits sub-aggregation 来达到这个目的:

  def bucket_for_order_amount(buckets, aggregations)
    buckets['order_range'] = {
      range: {
        field: :total,
        keyed: true, 
        ranges: [
            { to: 25.0 },
            { from: 25.0, to: 50.0 },
            { from: 50.0, to: 75.0 },
            { from: 75.0, to: 100.0 },
            { from: 100.0 }
        ]
      },
      aggs: {
        users: { top_hits: {} }
      }
    }     
  end