elastaicsearch demo 模糊查询,分页

  • 本文对elastaicsearch5.x版本的出现的精准,模糊,分页等查询demo,提供工具以供参考。

一、引用pom.xml

<dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.4.0</version>
        </dependency>
        <!--  s升级需要依赖的 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.4.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8.2</version>
        </dependency>
 <!-- gson 支持 json 串首字符大写的方式.fastjson 不支持-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.1</version>
        </dependency>

二、代码

  一、连接es客户端

package es;

import org.apache.log4j.Logger;
import org.elasticsearch.client.Client;

import java.net.UnknownHostException;

/**
 * @author Comsys-xiefg
 * @ClassName: ESClient
 * @Description: es 客户端
 * @date 2017年4月18日 下午1:48:10
 */
public class ESClient {
    private static Logger logger = Logger.getLogger(ESClient.class);
    /**
     * es服务器的host
     */
    private static String HOST="192.168.186.229";
    /**
     * es服务器暴露给client的port
     */
    private static Integer PORT=9300;

    private static String CLUSTER_NAME="cluster.name";

    private static String CLUSTER_NAME_VALUE="elasticsearch.cluster2";

    private static final String CLUSTER_CLIENT_SNIFF = "client.transport.sniff";

    private static final String SYSTEM_CONFIG_PATH = "system/config";

    private ESClient() {

    }
    /**
     * 获得连接
     *
     * @return
     * @throws UnknownHostException
     */
    public static synchronized Client getClient() {
        return ESClientFactory.getClient(CLUSTER_NAME, CLUSTER_NAME_VALUE, HOST, PORT);
    }

    public static void close(Client client) {
        ESClientFactory.close();
        if (client != null) {
            client.close();
        }
    }

}

2、创建es 工厂ESClientFactory

package es;

import org.elasticsearch.client.Client;

/**
 * Created by Dare on 2017/7/20.
 */
public class ESClientFactory {

	public static Client getClient(String clusterName, String clusterNameValue, String host, int port){
		EsClientBuilder clientBuilder = new EsClientBuilder();
		return clientBuilder.buildClient(clusterName,clusterNameValue,host,port);
	}

	public static void close() {
		EsClientBuilder.client.close();
	}

}

3、客户端创建EsClientBuilder

package es;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author xiefg
 * 
 */
public class EsClientBuilder {
	public static TransportClient client = null;
	public Client buildClient(String clusterName, String clusterNameValue, String host, int port) {
		try {
			Settings settings = Settings.builder()
					.put(clusterName, clusterNameValue).build();
			client = new PreBuiltTransportClient(settings);
			client.addTransportAddress(
					new InetSocketTransportAddress(InetAddress
							.getByName(host), port));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return client;
	}
}

 

4、索引对象

package es;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 
  * @ClassName: ESIndexObj
  * @Description: 索引对象
  * @author Comsys-xiefg
  * @date 2017年3月30日 下午4:26:04
  *
 */
public class ESIndexObj {
    /**
     * 索引
     */
    private String index;
    /**
     * 类型
     */
    private String type;
    /**
     * 关键词
     */
    private String keyWordName;
    /**
     * 关键词值
     */
    private String keyWordValue;
    /**
     * 开始时间
     */
    private String startTime;
    /**
     * 结束时间
     */
    private String endTime;
    
    private String dateFlag;
    /**
     * 排序列
     */
    private String sortColum;
    /**
     * 精准查询字段封装
     */
    private Map<String ,String> queryMap;
    /**
     * 通配符Map
     */
    private Map<String ,String> wildcardQueryMap;
    /**
     * 不包含 精准
     */
    private Map<String,Set> queryNotSetMap;
    /**
     * 相当于  a in ('','','')
     */
    private Map<String,List> queryShouldInList;

    public Map<String, List> getQueryShouldInList() {
        return queryShouldInList;
    }

    public void setQueryShouldInList(Map<String, List> queryShouldInList) {
        this.queryShouldInList = queryShouldInList;
    }



    public ESIndexObj() {

    }
    public ESIndexObj(String index, String type) {
        this.index = index;
        this.type = type;
    }

    public Map<String, Set> getQueryNotSetMap() {
        return queryNotSetMap;
    }

    public void setQueryNotSetMap(Map<String, Set> queryNotSetMap) {
        this.queryNotSetMap = queryNotSetMap;
    }

    public String getIndex() {
        return index;
    }

    public void setIndex(String index) {
        this.index = index;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getKeyWordName() {
        return keyWordName;
    }

    public void setKeyWordName(String keyWordName) {
        this.keyWordName = keyWordName;
    }

    public String getKeyWordValue() {
        return keyWordValue;
    }

    public void setKeyWordValue(String keyWordValue) {
        this.keyWordValue = keyWordValue;
    }

    public String getStartTime() {
        return startTime;
    }

    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }

    public String getEndTime() {
        return endTime;
    }

    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    public Map<String, String> getQueryMap() {
        return queryMap;
    }

    public void setQueryMap(Map<String, String> queryMap) {
        this.queryMap = queryMap;
    }

    public String getDateFlag() {
        return dateFlag;
    }

    public void setDateFlag(String dateFlag) {
        this.dateFlag = dateFlag;
    }

    public String getSortColum() {
        return sortColum;
    }

    public void setSortColum(String sortColum) {
        this.sortColum = sortColum;
    }

    public Map<String, String> getWildcardQueryMap() {
        return wildcardQueryMap;
    }

    public void setWildcardQueryMap(Map<String, String> wildcardQueryMap) {
        this.wildcardQueryMap = wildcardQueryMap;
    }
}

5、工具类ESUtils

package es;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ultrapower.secsight.view.bean.base.Pagination;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Comsys-xiefg
 * @ClassName: ESUtils
 * @Description: elasticsearch
 * @date 2017年3月23日 下午4:53:58
 */
public class ESUtils {

	/**
	 * 获得客户端
	 */
	public  static  Client client = ESClient.getClient();

	public static long searchTotal(ESIndexObj indexObj)
			throws IOException {
		String startTime = indexObj.getStartTime();
		String endTime = indexObj.getEndTime();
		BoolQueryBuilder bqb = new BoolQueryBuilder();
		//精准查找
		Map<String, String> queryMap = indexObj.getQueryMap();
		toQuery(bqb,queryMap);
		//对时间进行范围查询
		toRangeQuery(bqb,indexObj);
		SearchRequestBuilder srb = client.prepareSearch(indexObj.getIndex());
		srb.setTypes(indexObj.getType());
		srb.setQuery(bqb);
		if (StringUtils.isNotBlank(endTime)
				|| StringUtils.isNotBlank(startTime)) {
			srb.addSort(indexObj.getSortColum(), SortOrder.DESC);
		}
		SearchResponse response = srb.execute().actionGet();
		SearchHits hits = response.getHits();
		return hits.getTotalHits();
	}

	/**
	 * 查询所有
	 *
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@SuppressWarnings("rawtypes")
	public static List searchAll(ESIndexObj indexObj, Class clazz)
			throws IOException {
		String startTime = indexObj.getStartTime();
		String endTime = indexObj.getEndTime();
		BoolQueryBuilder bqb = new BoolQueryBuilder();
		//精准查找
		Map<String, String> queryMap = indexObj.getQueryMap();
		toQuery(bqb,queryMap);
		//通配符
		Map<String, String>	wildcardMap=indexObj.getWildcardQueryMap();
		toWildcardQuery(bqb,wildcardMap);
		//对时间进行范围查询
		toRangeQuery(bqb,indexObj);
		SearchRequestBuilder srb = client.prepareSearch(indexObj.getIndex());
		srb.setTypes(indexObj.getType());
		srb.setQuery(bqb);
		if (StringUtils.isNotBlank(endTime)
				|| StringUtils.isNotBlank(startTime)) {
			//根据字段排序
			srb.addSort(indexObj.getSortColum(), SortOrder.DESC);
		}
		SearchResponse response = srb.execute().actionGet();
		SearchHits hits = response.getHits();
		int totalRecordNum = (int) hits.getTotalHits();
		// 设置总数,es支持一次查询最大10000条,再多出现异常
		totalRecordNum=totalRecordNum>10000?10000:totalRecordNum;
		srb.setFrom(0).setSize(totalRecordNum).setExplain(true);
		SearchHits hitsAll = srb.execute().actionGet().getHits();
		List<Object> noauthList = new ArrayList<Object>();
		Gson gson = new GsonBuilder()
				.setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
				.create();
		for (SearchHit searchHit : hitsAll) {
			Map<String, Object> source = searchHit.getSource();
			/**
			 * 采用gson,因为fastjson 不支持 首字符大写的 json 串
			 */
			Object entity =gson.fromJson(gson.toJson(source),clazz);
			noauthList.add(entity);
		}
		return noauthList;
	}

	/***
	 * @param pageSize
	 * @param pageNo
	 * @param clazz
	 * @param indexObj
	 * @return Pagination 返回类型
	 * @throws Exception 设定文件
	 * @throws
	 * @Title: findByPage
	 * @Description: 分页查询
	 */
	@SuppressWarnings({"rawtypes", "unchecked"})
	public static Pagination findByPage(Integer pageSize, Integer pageNo,
										Class clazz, ESIndexObj indexObj) throws Exception {
		Pagination page = new Pagination<>();
		pageNo = null == pageNo ? 1 : pageNo;// 当前页
		page.setPageCount(pageNo);
		page.setPageSize(pageSize);
		SearchData searchData = searchData(indexObj, pageSize, pageNo, clazz);
		page.setTotalRecordNum(searchData.getTotalRecordNum());// 总记录数
		int totalPageNum = 1;
		int totalRecordNum = searchData.getTotalRecordNum();
		if (totalRecordNum > pageSize) {
			totalPageNum = totalRecordNum / pageSize + 1;
		}
		page.setTotalPageNum(totalPageNum);// 设置总页数
		page.setDatas(searchData.getSearchList());
		return page;

	}

	@SuppressWarnings("rawtypes")
	private static SearchData searchData(ESIndexObj indexObj, Integer pageSize,
										 Integer pageNo, Class entityClass) throws UnknownHostException {

		// 构建查询条件
		SearchRequestBuilder srb = getQueryBuilder(indexObj, pageSize, pageNo,
				client);
		SearchResponse response = srb.execute().actionGet();
		SearchHits hits = response.getHits();
		int totalRecordNum = (int) hits.getTotalHits();
		List<Object> list = new ArrayList<Object>();
		Gson gson = new GsonBuilder()
				.setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
				.create();
		for (SearchHit searchHit : hits) {
			Map<String, Object> source = searchHit.getSource();
			//Gson gson=new Gson();
			Object entity =gson.fromJson(gson.toJson(source),entityClass);
			list.add(entity);
		}
		SearchData searchData = new SearchData();
		searchData.setSearchList(list);
		searchData.setTotalRecordNum(totalRecordNum);
		return searchData;
	}

	/**
	 * 执行搜索(带分组)
	 *
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> searcherGroup(ESIndexObj indexObj,
													Integer pageSize, Integer pageNo, Class<?> entityClass,
													String aggsField) throws Exception {
		Client client = ESClient.getClient();
		SearchRequestBuilder searchRequestBuilder = getQueryBuilder(indexObj,
				pageSize, pageNo, client);
		return ESClientUtils.searchGroup(searchRequestBuilder, pageSize, pageNo, entityClass, aggsField);
	}

	/**
	 * 构建查询条件(带分页)
	 *
	 * @param indexObj
	 * @param pageSize
	 * @param pageNo
	 * @param client
	 * @return
	 */
	private static SearchRequestBuilder getQueryBuilder(ESIndexObj indexObj,
														Integer pageSize, Integer pageNo, Client client) {
		String startTime = indexObj.getStartTime();
		String endTime = indexObj.getEndTime();
		BoolQueryBuilder bqb = new BoolQueryBuilder();
		//精准查找相应字段
		Map<String, String> queryMap = indexObj.getQueryMap();
		toQuery(bqb,queryMap);
        //通配符wildcard
	    Map<String, String>	wildcardMap=indexObj.getWildcardQueryMap();
		toWildcardQuery(bqb,wildcardMap);
		//不包含 精准
		Map<String, Set> queryNotSetMap = indexObj.getQueryNotSetMap();
		toMustNotQuery(bqb,queryNotSetMap);
	    // 相当于  a in ('','','')
		Map<String, List> shouldInList = indexObj.getQueryShouldInList();
		toTermsQuery(bqb,shouldInList);
        //对时间进行范围查询
		toRangeQuery(bqb,indexObj);

		SearchRequestBuilder srb = client.prepareSearch(indexObj.getIndex());
		srb.setTypes(indexObj.getType());
		srb.setQuery(bqb);
		srb.setFrom((pageNo - 1) * pageSize).setSize(pageSize).setExplain(true);
		if (StringUtils.isNotBlank(startTime)
				|| StringUtils.isNotBlank(endTime)) {
			if(indexObj.getSortColum()!=null){
				srb.addSort(indexObj.getSortColum(), SortOrder.DESC);
			}
		}
		return srb;
	}

    /**
	 * @desc  一个字段 不包含
	 * @param bqb
	 * @param queryNotSetMap
	 */
	private static void toMustNotQuery(BoolQueryBuilder bqb ,Map<String ,Set> queryNotSetMap){
		if(queryNotSetMap!=null){
			for (Map.Entry<String, Set> entry : queryNotSetMap.entrySet()) {
				String keyStr= entry.getKey().toString();
				Set<String> setVal=entry.getValue();
				for (String str : setVal) {
					bqb.mustNot(QueryBuilders.termQuery(keyStr, str));
				}
			}
		}
	}

	/**
	 * @desc 通配符匹配  例如 *hello*
	 * @param bqb
	 * @param wildcardMap
	 */
	private static void toWildcardQuery(BoolQueryBuilder bqb ,Map<String ,String> wildcardMap){
		Set<String> keySet = null;
		if (wildcardMap != null && (keySet = wildcardMap.keySet()) != null) {
			for (String key : keySet) {
				bqb.must(QueryBuilders.wildcardQuery(key, "*"+wildcardMap.get(key)+"*"));
			}
		}
	}


	/**
	 * @desc  相当于 a  in(‘1’,‘2’)
	 * @param bqb
	 * @param termsInList
	 */
	private static void toTermsQuery(BoolQueryBuilder bqb ,Map<String ,List> termsInList){
		if (termsInList != null && (termsInList.keySet()) != null) {
			for (Map.Entry<String, List> entry : termsInList.entrySet()) {
				String keyStr = entry.getKey().toString();
				List<String> setVal = entry.getValue();
				bqb.must(QueryBuilders.termsQuery(keyStr,setVal));
			}
		}
	}


	/**
	 * @desc  精准查找 相应的字段
	 * @param bqb
	 * @param queryMap
	 */
	private static void toQuery(BoolQueryBuilder bqb ,Map<String ,String> queryMap){
		Set<String> keySet = null;
		if (queryMap != null && (keySet = queryMap.keySet()) != null) {
			for (String key : keySet) {
				bqb.must(QueryBuilders.termQuery(key, queryMap.get(key)));
			}
		}
	}


	/**
	 * @desc  精准查找  对 时间范围
	 * @param bqb
	 * @param indexObj
	 */
	private static void toRangeQuery(BoolQueryBuilder bqb , ESIndexObj indexObj){
		// 关键字段,关键词
		String startTime = indexObj.getStartTime();
		String endTime = indexObj.getEndTime();
		String dateFlag = indexObj.getDateFlag();
		if (StringUtils.isNotBlank(startTime)
				&& StringUtils.isNotBlank(dateFlag)) {
			bqb.must(QueryBuilders.rangeQuery(dateFlag).gte(startTime));
		}
		if (StringUtils.isNotBlank(endTime) && StringUtils.isNotBlank(dateFlag)) {
			bqb.must(QueryBuilders.rangeQuery(dateFlag).lte(endTime));
		}
	}


	/**
	 * 对象转数组
	 *
	 * @param obj
	 * @return
	 */
	public static byte[] toByteArray(Object obj) {
		byte[] bytes = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(obj);
			oos.flush();
			bytes = bos.toByteArray();
			oos.close();
			bos.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return bytes;
	}

}

6、分页

package com.ultrapower.secsight.view.bean.base;

import java.util.List;

/**
*
* @Title:Pagination
* @Description:分页实体类
* @author xiefg
 */
public class Pagination<T> {
	/**
	 * 每页显示总记录数,默认为10
	 */
	private int pageSize = 10;
	
	/**
	 * 当前页数:默认值从1开始的
	 */
	private int pageCount = 1;
	
	/**
     * 总记录数
     */
    private long totalRecordNum;
    
	/**
     * 总页数
     */
    private int totalPageNum;
    
    /**
     * 分页查询到的数据
     */
    private List<T> datas;
    
    /**
     * 操作错误信息
     */
    private String errorMsg;
    
	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public long getTotalRecordNum() {
		return totalRecordNum;
	}

	public void setTotalRecordNum(long totalRecordNum) {
		this.totalRecordNum = totalRecordNum;
	}

	public int getTotalPageNum() {
		return totalPageNum;
	}

	public void setTotalPageNum(int totalPageNum) {
		this.totalPageNum = totalPageNum;
	}

	public List<T> getDatas() {
		return datas;
	}

	public void setDatas(List<T> datas) {
		this.datas = datas;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	@Override
	public String toString() {
		return "Pagination [pageSize=" + pageSize + ", pageCount=" + pageCount + ", totalRecordNum=" + totalRecordNum
				+ ", totalPageNum=" + totalPageNum + "]";
	}
	
}

7、分页封装返回数据SearchData

package es;

import java.util.ArrayList;
import java.util.List;

/**
 * 
  * @ClassName: SearchData
  * @Description: 搜索返回的数据实体
  * @author Comsys-xiefg
  * @date 2017年3月27日 下午5:46:25
  *
 */
public class SearchData {
    
    private int totalRecordNum;
    
    private List<?> searchList=new ArrayList<>();

    public int getTotalRecordNum() {
        return totalRecordNum;
    }

    public void setTotalRecordNum(int totalRecordNum) {
        this.totalRecordNum = totalRecordNum;
    }

    public List<?> getSearchList() {
        return searchList;
    }

    public void setSearchList(List<?> searchList) {
        this.searchList = searchList;
    }
    
    

}

针对以上是整个工具用的,后续需要调用相关API 

ESUtils.findByPage(Integer pageSize, Integer pageNo,
                           Class clazz, ESIndexObj indexObj
)

参数说明:

pageSize 设置页数大小。

pageNo设置第几页 。

Class 为需要查询的相关对象(封装的字段要和elasticserach索引字段对应相同) 

ESIndexObj 为过滤对象,可以设置索引名称,类型,精准,模糊,in 等查询支持 

 

三、测试demo

1、es索引数据如下图:

 

2、索引实体类

package com.ultrapower.secsight.view.bean.base;

import java.io.Serializable;

public class AttackLog implements Serializable {
    private String logId;
    private String srcip;
    private String srcPort;
    private String destip;
    private String destPort;
    private String proto;
    private String time;
    private String type;
    private String subject;
    private String year;
    private String month;
    private String week;
    private String day;
    private Long   dayofweek;
    private Long   hour;
    private String count;
    private String eventkmid;
    private String biz;
    private String host;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getBiz() {
        return biz;
    }

    public void setBiz(String biz) {
        this.biz = biz;
    }

    public AttackLog() {
    }

    public String getLogId() {
        return logId;
    }

    public void setLogId(String logId) {
        this.logId = logId;
    }

    public String getSrcip() {
        return srcip;
    }

    public void setSrcip(String srcip) {
        this.srcip = srcip;
    }

    public String getSrcPort() {
        return srcPort;
    }

    public void setSrcPort(String srcPort) {
        this.srcPort = srcPort;
    }

    public String getDestip() {
        return destip;
    }

    public void setDestip(String destip) {
        this.destip = destip;
    }

    public String getDestPort() {
        return destPort;
    }

    public void setDestPort(String destPort) {
        this.destPort = destPort;
    }

    public String getProto() {
        return proto;
    }

    public void setProto(String proto) {
        this.proto = proto;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getMonth() {
        return month;
    }

    public void setMonth(String month) {
        this.month = month;
    }

    public String getWeek() {
        return week;
    }

    public void setWeek(String week) {
        this.week = week;
    }

    public String getDay() {
        return day;
    }

    public void setDay(String day) {
        this.day = day;
    }

    public Long getDayofweek() {
        return dayofweek;
    }

    public void setDayofweek(Long dayofweek) {
        this.dayofweek = dayofweek;
    }

    public Long getHour() {
        return hour;
    }

    public void setHour(Long hour) {
        this.hour = hour;
    }

    public String getCount() {
        return count;
    }

    public void setCount(String count) {
        this.count = count;
    }

    public String getEventkmid() {
        return eventkmid;
    }

    public void setEventkmid(String eventkmid) {
        this.eventkmid = eventkmid;
    }




    @Override
    public String toString() {
        return "AttackLog{" +
                "logId='" + logId + '\'' +
                ", srcip='" + srcip + '\'' +
                ", srcPort='" + srcPort + '\'' +
                ", destip='" + destip + '\'' +
                ", destPort='" + destPort + '\'' +
                ", proto='" + proto + '\'' +
                ", time='" + time + '\'' +
                ", type='" + type + '\'' +
                ", subject='" + subject + '\'' +
                ", year='" + year + '\'' +
                ", month='" + month + '\'' +
                ", week='" + week + '\'' +
                ", day='" + day + '\'' +
                ", dayofweek=" + dayofweek +
                ", hour=" + hour +
                ", count='" + count + '\'' +
                ", eventkmid='" + eventkmid + '\'' +
                ", biz='" + biz + '\'' +
                ", host='" + host + '\'' +
                '}';
    }
}

3、Test类

package es;

import com.ultrapower.secsight.constant.Systemconstant;
import com.ultrapower.secsight.util.date.LocalDateUtil;
import com.ultrapower.secsight.util.xls.ExcelUtil;
import com.ultrapower.secsight.view.bean.base.AttackLog;
import com.ultrapower.secsight.view.bean.base.Pagination;
import org.junit.Test;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;

/**
 * @author xiefg
 * @create 2018-07-20 15:00
 * @desc
 **/

public class EsTest {

    @Test
    public void testPage() {
        /**
         *   分页查询
         */
        ESIndexObj esIndexObj=new ESIndexObj();
        esIndexObj.setIndex("attacklog");
        esIndexObj.setType("attacklog");
        /***
         * 设置精准查找 过滤字段
         */
        Map queryMap=new HashMap();
        queryMap.put("destip","172.16.6.212");
        esIndexObj.setQueryMap(queryMap);
        try {
         Pagination<AttackLog> pagination= ESUtils.findByPage(10,1,AttackLog.class,esIndexObj);
          List<AttackLog> attackLogList=pagination.getDatas();
            //函数式编程遍历对象
            attackLogList.stream().forEach(attackLog -> {
                System.out.println(attackLog.toString());
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    
}

 

结果如下:

AttackLog{logId='4295239709', srcip='124.126.244.146', srcPort='0', destip='172.16.6.212', destPort='0', proto='HTTP', time='2017-12-06 09:58:43', type='HTTP_SQL注入攻击', subject='SQL注入攻击', year='2017', month='201712', week='201749', day='20171206', dayofweek=3, hour=9, count='255', eventkmid='6', biz='null', host='null'}
AttackLog{logId='4295239709', srcip='', srcPort='', destip='172.16.6.212', destPort='80', proto='', time='2017-12-06 15:07:00', type='waf_log_urihits', subject='URL攻击', year='2017', month='201712', week='201749', day='20171206', dayofweek=3, hour=15, count='', eventkmid='6', biz='null', host='null'}
AttackLog{logId='4295239709', srcip='124.126.244.146', srcPort='0', destip='172.16.6.212', destPort='0', proto='HTTP', time='2017-12-07 09:14:17', type='HTTP_SQL注入攻击', subject='SQL注入攻击', year='2017', month='201712', week='201749', day='20171207', dayofweek=4, hour=9, count='255', eventkmid='6', biz='null', host='null'}
AttackLog{logId='4295239709', srcip='', srcPort='', destip='172.16.6.212', destPort='80', proto='', time='2017-12-07 09:07:00', type='waf_log_urihits', subject='URL攻击', year='2017', month='201712', week='201749', day='20171207', dayofweek=4, hour=9, count='', eventkmid='6', biz='null', host='null'}
AttackLog{logId='4295239709', srcip='220.181.125.98', srcPort='11041', destip='172.16.6.212', destPort='80', proto='HTTP', time='2017-12-06 09:58:43', type='HTTP_sogou_spider_爬取网页', subject='sogou_spider爬取网页', year='2017', month='201712', week='201749', day='20171206', dayofweek=3, hour=9, count='', eventkmid='6', biz='null', host='null'}
AttackLog{logId='4295239709', srcip='220.181.125.98', srcPort='11041', destip='172.16.6.212', destPort='80', proto='HTTP', time='2017-12-07 09:14:17', type='HTTP_sogou_spider_爬取网页', subject='sogou_spider爬取网页', year='2017', month='201712', week='201749', day='20171207', dayofweek=4, hour=9, count='', eventkmid='6', biz='null', host='null'}

如图为经过精准过滤后的数据

以上工具,针对不同的索引,只需要对象和索引字段对应,调用分页方法即可。

其它查询总数后续继续........

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值