Elasticsearch Nest聚合分组取最小值查询

取产品的最低价

注:产品价格为区间价格,nested类型

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "model": "LP3985IM5X-3.3"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 10,
  "sort": [],
  "aggs": {
    "top_tag_hits": {
      "terms": {
        "field": "model"
      },
      "aggs": {
        "stockprice": {
          "nested": {
            "path": "stockPrice"
          },
          "aggs": {
            "minprice": {
              "min": {
                "field": "stockPrice.price"
              }
            }
          }
        }
      }
    }
  }
}
public PUB_StockSearchResult SearchMinPrice(PUB_StockSearch param)
        {
            PUB_StockSearchResult result = new PUB_StockSearchResult();
            result.ResultList = new List();
            if (param.ModelArr == null || param.ModelArr.Length == 0)
            {
                return result;
            }
            QueryContainer query = new TermsQuery() { Field = ES_PUB_StockField.Model, Terms = param.ModelArr };
            TermsAggregation aggs = new TermsAggregation("top_tag_hits")
            {
                Field = ES_PUB_StockField.Model,
                Aggregations = new NestedAggregation("stockprice")
                {
                    Path = "stockPrice",
                    Aggregations = new MinAggregation("minprice", "stockPrice.price")
                }
            };
            var searchRequest = new SearchRequest();
            searchRequest.Query = query;
            searchRequest.From = 0;
            searchRequest.Aggregations = aggs;
            searchRequest.Size = 1000;
            var response = client.Search(searchRequest);
            result.Total = response.Total;

            var states = response.Aggs.Terms("top_tag_hits");

            foreach (var state in states.Buckets)
            {
                var topStateHits = state.Nested("stockprice").Min("minprice").Value;
                if (topStateHits != null)
                {
                    ES_PUB_StockResult resultItem = new ES_PUB_StockResult();
                    resultItem.Model = state.Key;
                    resultItem.Price = Convert.ToDecimal(topStateHits);
                    result.ResultList.Add(resultItem);
                }
            }
            return result;
        }


你可能感兴趣的:(ElasticSearch)