一、关键词查询
/**
* es中查询日志* @param page
* @param esAppLog
* @return
*/
public List<EsAppLog> getEsAppLogs(Page<EsAppLog> page, EsAppLog esAppLog) {
//前端参数
String index = esAppLog.getIndex();
String keyword = esAppLog.getKeyWord();
//查询的索引数组
SearchRequestBuilder responsebuilder = client.prepareSearch(index.split(","));//关键词查询
if(StringUtils.isNotEmpty(keyword)){responsebuilder.setQuery(QueryBuilders.matchQuery("message", keyword));
}
if(null != page){
int size = page.getPageSize();
int start = (page.getPageNo() - 1) * size;
responsebuilder.setFrom(start).setSize(size);
}
//执行查询
SearchResponse myresponse = responsebuilder.setExplain(true).get();
SearchHits hits = myresponse.getHits();//总条数
if(null != page){
page.setCount(hits.getTotalHits());
}
//转换成对象
List<EsAppLog> logs = new ArrayList<EsAppLog>();EsAppLog log = null;
for (int i = 0; i < hits.getHits().length; i++) {
Map<String,Object> item = hits.getHits()[i].getSource();
log = new EsAppLog();
log.setIp((String)item.get("host"));
log.setTime((String)item.get("@timestamp"));
log.setLogName((String)item.get("path"));
log.setLogContent((String)item.get("message"));
logs.add(log);
}
return logs;
}
二、多条件查询并返回指定字段
public void getCPUEsData(){
//索引值
SearchRequestBuilder responsebuilder = client.prepareSearch("system");
//返回指定字段
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
String[] fields = {"@timestamp","value"};
FetchSourceContext sourceContext = new FetchSourceContext(fields);
searchSourceBuilder.fetchSource(sourceContext);
responsebuilder.setSource(searchSourceBuilder);
//collectd=cpu and type_instance=system条件查询
responsebuilder.setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("collectd_type", "cpu")).must(QueryBuilders.termQuery("type_instance", "system")));
//执行查询
SearchResponse myresponse = responsebuilder.get();
SearchHits hits = myresponse.getHits();
for (int i = 0; i < hits.getHits().length; i++) {
Map<String,Object> item = hits.getHits()[i].getSource();
System.out.println(item);
}
}