需求是這樣的:
近7天的用戶登陸統計,根據日期來返回的要是data:[{date:“2021-04-01”,count:“1”}]
@Autowired
private ElasticsearchTemplate elasticsearchTemplate
;SimpleDateFormat formater
= new SimpleDateFormat("yyyy-MM-dd");
String startTime
= DateUtil
.getWeekFromNow();
String endTime
= formater
.format(new Date());
List
<LoginLogDoc> loginLogDocList
= new ArrayList<>();
List
<EchartsVO> echartsVOS
= new ArrayList<>();
BoolQueryBuilder bqb
= QueryBuilders
.boolQuery();
bqb
.must(QueryBuilders
.rangeQuery("createTime").from(startTime
).to(endTime
));
SearchQuery searchQuery
= new NativeSearchQueryBuilder().withQuery(bqb
).withIndices("login_log").withTypes("login_log").withSearchType(SearchType
.DEFAULT
).build();
loginLogDocList
= elasticsearchTemplate
.queryForList(searchQuery
,LoginLogDoc
.class);
for (LoginLogDoc loginLogDoc
: loginLogDocList
) {loginLogDoc
.setCreateTime(loginLogDoc
.getCreateTime().substring(0,10));}
Map resultMap
= new HashMap();
for (LoginLogDoc loginLogDoc
: loginLogDocList
) {loginLogDoc
.setCreateTime(loginLogDoc
.getCreateTime());Object obj
= resultMap
.get(loginLogDoc
.getCreateTime());if(obj
!= null
){resultMap
.put(loginLogDoc
.getCreateTime(), ((Integer
) obj
+ 1));}else{resultMap
.put(loginLogDoc
.getCreateTime(), 1);}
}
resultMap
.forEach((key
, value
) -> {EchartsVO echartsVO
= new EchartsVO();echartsVO
.setDate((String
) key
);echartsVO
.setCount((Integer
) value
);echartsVOS
.add(echartsVO
);
});
login_log 是我們的實體類的名稱:
@Getter
@Setter
@ToString
@Document(indexName
= "login_log", type
= "login_log", createIndex
= false)
public class LoginLogDoc implements Serializable {@Idprivate String loginLogId
;private Integer userId
;private String createTime
;
}
有什么問題就給我留言吧
總結
以上是生活随笔為你收集整理的ElasticSearch Java SpringBoot根据时间范围分组求和的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。