我正在使用 Elsaticsearch Spring Data。我有一個自定義存盤庫,它根據docs上的示例使用 ElasticsearchOperations 。我需要一些聚合查詢結果,我成功地得到了預期的結果。但我需要將這些結果映射到模型。但目前我無法訪問 AggregationsContainer 的內容。
override fun getStats(startTime: Long, endTime: Long, pageable: Pageable): AggregationsContainer<*>?
{
val query: Query = NativeSearchQueryBuilder()
.withQuery(QueryBuilders.rangeQuery("time").from(startTime).to(endTime))
.withAggregations(AggregationBuilders.sum("discount").field("discount"))
.withAggregations(AggregationBuilders.sum("price").field("price"))
.withPageable(pageable)
.build()
val searchHits: SearchHits<Product> = operations.search(query, Product::class.java)
return searchHits.aggregations
}
我回傳以下代碼的結果:
val stats = repository.getTotalStats(before, currentTime, pageable)?.aggregations()
結果是:
{
"asMap": {
"discount": {
"name": "discount",
"metadata": null,
"value": 8000.0,
"valueAsString": "8000.0",
"type": "sum",
"fragment": true
},
"price": {
"name": "price",
"metadata": null,
"value": 9000.0,
"valueAsString": "9000.0",
"type": "sum",
"fragment": true
}
},
"fragment": true
}
如何將上述輸出轉換為預期的輸出模型,如下所示?因為我測驗的內容aggregations()是無法訪問的,型別是Any:
{
"priceSum":9000.0,
"discountSum":8000
}
uj5u.com熱心網友回復:
Elasticsearch RestHighLevelClient 類中沒有資料模型用于聚合,Spring Data Elasticsearch 中沒有on。因此原始Aggregations物件被回傳給呼叫者(包含在那個中AggregationContainer,因為它會隨著新的新客戶端實作而改變,然后容器將保存一個不同的物件)。
你必須自己決議這個,我在另一個問題的回答中有一些東西(https://stackoverflow.com/a/63105356/4393565)。對您來說有趣的是傳遞聚合的最后一個代碼塊。您基本上必須遍歷元素,將它們轉換為適當的型別并評估它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/398104.html
