2015-10-18 63 views
1

我試圖通過產品編號查詢我在Elasticsearch數據庫中記錄的產品的定價統計信息。定價可能是新的,二手或翻新產品,所以我希望過濾條件。條件過濾器在Marvel基於兩個具有新條件的價格文檔返回統計信息時用作JSON查詢。Spring Elasticsearch Aggregation Filtering Not Working

當我嘗試使用Java API執行類似操作時,我獲得了基於4個文檔的統計信息,其中包括2個新的和2個翻新的。

任何人都可以請確定我在做什麼錯在下面的Java代碼?

謝謝。

這裏的工作JSON查詢:

GET /stats/price/_search 
{ 
    "query": { 
    "match_phrase": {"mpc": "MGTX2LL/A"} 
    }, 
    "size": 0, 
    "aggs" : { 
     "low_price_stats" : { 
     "filter": { 
      "term" : { "condition" : "new"} 
     }, 
     "aggs" : { 
      "price_stats" : { "extended_stats" : { "field" : "price" } } 
     } 
    } 
    } 
} 

而問題的Java:

public Aggregations aggByManufacturerPartNumber(String mpn) { 

    SearchQuery searchQuery = new NativeSearchQueryBuilder() 
     .withIndices("stats") 
     .withTypes("price") 
     .withQuery(termQuery("mpn", mpn)) 
     .withFilter(
      FilterBuilders.termFilter("condition", "New") 
     ) 
     .addAggregation(AggregationBuilders.extendedStats("stats_agg").field("price")) 
     .build(); 

    Aggregations aggregations = elasticsearchTemplate.query(searchQuery, new ResultsExtractor<Aggregations>() { 
     @Override 
     public Aggregations extract(SearchResponse response) { 
      return response.getAggregations(); 
     } 
    }); 

    return aggregations; 
} 

回答

1

在Java代碼中你只是建立price_stats子聚集而不其父filter聚集。對withFilter的調用將在查詢級別創建過濾器,而不是在聚合級別。符合您的JSON查詢正確的Java代碼將是這樣的:

// build top-level filter aggregation 
FilterAggregationBuilder lowPriceStatsAgg = AggregationBuilders.filter("low_price_stats") 
    .filter(FilterBuilders.termFilter("condition", "new")); 

// build extended stats sub-aggregation 
lowPriceStatsAgg.subAggregation(AggregationBuilders.extendedStats("stats_agg").field("price")); 

// build query 
SearchQuery searchQuery = new NativeSearchQueryBuilder() 
    .withIndices("stats") 
    .withTypes("price") 
    .withQuery(termQuery("mpn", mpn)) 
    .addAggregation(lowPriceStatsAgg) 
    .build(); 

// then get the results 
Aggregations aggs = response.getAggregations(); 
Filter lowPriceStats = aggs.get("low_price_stats"); 
ExtendedStats statsAgg = lowPriceStats.get("stats_agg"); 

另外,也請注意,在你的JSON查詢您的mpc領域有match_phrase,而在Java代碼中你對一個term查詢mpn字段。所以你可能也需要解決這個問題,但上面的代碼只修復了聚合部分。

+0

好的,謝謝!我快到了。子聚合看起來是lowPriceStatsAgg.subAggregation(...)。查詢和提取器後,我得到一個空值。因爲它是一個子集合,我需要製作一個不同的ResultExtractor嗎? –