15.1 在 gmall-publish 子模块中读取 ES 中数据
15.1.1 在PublisherService
中添加方法
package com.atguigu.dw.gmallpublisher.service
trait PublisherService {
def getSaleDetailAndAggResultByAggField(date: String,
keyword: String,
startPage: Int,
size: Int,
aggField: String,
aggSize: Int): Map[String, Any]
}
15.1.2 在PublisherServiceImp
中实现上述方法
override def getSaleDetailAndAggResultByAggField(date: String, keyword: String, startPage: Int, size: Int, aggField: String, aggSize: Int): Map[String, Any] = {
val searchDSL =
s"""
|{
| "from": ${(startPage - 1) * size},
| "size": $size,
| "query": {
| "bool": {
| "filter": {
| "term": {
| "dt": "$date"
| }
| }
| , "must": [
| {"match": {
| "sku_name": {
| "query": "$keyword",
| "operator": "and"
| }
| }}
| ]
| }
| }
| , "aggs": {
| "groupby_$aggField": {
| "terms": {
| "field": "user_$aggField",
| "size": $aggSize
| }
| }
| }
|}
""".stripMargin
val search: Search = new Search.Builder(searchDSL)
.addIndex("gmall_sale_detail")
.addType("_doc")
.build()
val client: JestClient = MyESUtil.getClient()
val result: SearchResult = client.execute(search)
val total: Integer = result.getTotal
val detailList = List[Map[String, Any]]()
val hits: util.List[SearchResult#Hit[util.HashMap[String, Any], Void]] = result.getHits(classOf[util.HashMap[String, Any]])
import scala.collection.JavaConversions._
for (hit <- hits) {
val source: util.HashMap[String, Any] = hit.source
detailList.add(source.toMap)
}
var aggMap = Map[String, Long]()
val buckets = result.getAggregations.getTermsAggregation(s"groupby_$aggField").getBuckets
for (bucket <- buckets) {
aggMap += bucket.getKey -> bucket.getCount()
}
Map("total" -> total, "aggMap" -> aggMap, "detail" -> detailList)
}