ElastaticSearch----es聚合,並獲取query的排序結果


使用es聚合時,有時還需要獲取query(或filter) 的結果。

比如統計各個地區編碼的營業額,得到了聚合的統計結果,還想知道query結果中對應的地區名稱,並根據營業額進行排序,

這時可以使用 top_hits。

top_hits屬性

top_hits有以下的屬性:

    from - 從第幾個結果開始獲取。
    size - 每個桶返回的query結果的數量。默認情況下,返回前三個匹配的結果。
    sort - 根據字段進行排序。默認情況下,按主查詢的分數排序。

top_hits的DSL

格式如下:

{
  "size" : 0,
  "query" : {  },
  "aggregations" : {
    "自己命名的聚合名稱" : {
      "terms" : {
        "field" : "聚合字段",
        "size" : 10000,
        "order" : {
          "_term" : "asc"
        }
      },
      "aggregations" : {
        "hits" : {
          "top_hits" : {
	     "sort": [
              {
                "排序字段": {
                  "order": "desc"
                }
              }
            ],
            "from" : 0,
            "size" : 5
          }
        },
		
        "自己命名的聚合統計的名稱" : {
          "sum" : {
            "field" : "聚合統計字段"
          }
        }
      }
    }
  }
} 

示例如下:

{
  "size" : 0,
  "query" : {  },
  "aggregations" : {
    "agg_area" : {
      "terms" : {
        "field" : "area",
        "size" : 10000,
        "order" : {
          "_term" : "asc"
        }
      },
      "aggregations" : {
        "hits" : {
          "top_hits" : {
	    "sort": [
              {
                "amount": {
                  "order": "desc"
                }
              }
            ],
            "from" : 0,
            "size" : 5
          }
        },
		
        "area_sum" : {
          "sum" : {
            "field" : "amount"
          }
        }
      }
    }
  }
} 

top_hits的java代碼

如下所示:

    public static String getTopHitsDSL() {

        SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource();

        AggregationBuilder areaCodeAgg = AggregationBuilders.terms("agg_area").field("area")
	        .order(Terms.Order.aggregation(TERM, true)).size(10000)
                .subAggregation(AggregationBuilders.topHits(HITS).sort("amount").size(5))
                .subAggregation(AggregationBuilders.sum("area_sum").field("amount"));

        return searchSourceBuilder.query().aggregation(areaCodeAgg).size(0).toString();
    }

參考資料:

http://itindex.net/detail/60468-elasticsearch-top-hits


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM