elasticsearch java代码使用

elasticsearch  java代码使用  

java 接口

package com.lty.dispatch.framework.elasticsearch;

import com.lty.dispatch.framework.elasticsearch.entity.ChildQueryModel;
import com.lty.dispatch.framework.elasticsearch.entity.GroupResult;
import com.lty.dispatch.framework.elasticsearch.entity.SearchResult;

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


/**
 * 基于es的搜索服务接口
 * 创建索引时所有的时间字段转化为long型,ms即可
 * @author 江贤
 *
 */
public interface SearchService {

	/**
	 * 根据单表搜索记录,t表示对象,基于其中的对象属性进行匹配
	 * @param pageSize 从第几条开始查 (当前页数-1)*每页条数
	 * @param pageNum	每页条数
	 * @param t	对象,封装了条件,条件为对象中的属性,对象中每个属性的值可以形成and或or查询,
	 * 		比如:如果是and关系查询prop=and:条件1 条件2,如果是or关系查询prop=or:条件1 条件2
	* @param rangeMap 需要过滤的条件,一般用于范围查询,
	 *     系统根据用户传入的参数进行判断,例如传入的参数为
	 *     Map<String,String> rangeMap = new HashMap<String,String>();
	 *     //范围
	 *     rangeMap.put("notice_time", "between:v1,v2");
	 *     //小于等于
	 *     rangeMap.put("xxfield","lte:v");
	 *     //大于等于
	 *     rangeMap.put("xxfield","gte:v");
	 *     其中key必须为t中的属性
	 *     对于复杂的范围查询,例如一个字段需要对应多个范围或多个条件,则value为
	 *     between:v1,v2 gte:v3 between v4,v5 lte:v6
	 *     当然可以任意组合,只要符合格式要求即可
	 * @param type 映射类型
	 * @param indexName 索引名称
	 * @param clazz t的具体类型
	 * @param highLight 高亮,如果不需要可以为null
	 * @param sortMap 排序,可以为多字段排序,如果不需要可以为null
	 * @return
	 */
	public <T> SearchResult<T> search(int pageSize, int pageNum, String[] indexName,
                                      String type, T t, Class<T> clazz, Map<String, String> rangeMap,
                                      Map<String, String> sortMap, boolean highLight);
	/**
	 * 根据id精确查询某条记录
	 * @param indexName
	 * @param type
	 * @param clazz
	 * @param id id字段名称
	 * @param value id字段值
	 * @return
	 */
	public <T> T searchById(String indexName, String type, Class<T> clazz, String id, String value);
	/**
	 * 获取分组统计信息
	 * @param indexName 索引名称
	 * @param type 映射类型
	 * @param t	条件封装对象
	 * @param rangeMap 范围查询条件
	 * @param groupName	分组字段
	 * @return
	 */
	public <T> List<GroupResult> groupSearch(String indexName, String type,
                                             T t, Map<String, String> rangeMap, String groupName);
	/**
	 * 查询总数
	 * @param indexName
	 * @param type
	 * @param t
	 * @param clazz
	 * @param rangeMap
	 * @return
	 */
	public <T> long count(String indexName, String type, T t,
                          Class<T> clazz, Map<String, String> rangeMap);
	
	/**
	 * 根据父子条件深度查询,可以实现一个主表,多个子表的多关系联合查询
	 * 返回结果全都封装到父对象中
	 * @param indexName 索引名称
	 * @param parentType 主集映射类型
	 * @param parentBean  主对象查询条件
	 * @param parentType 主对象类型
	 * @param parentRangeMap 主对象范围查询条件
	 * @param parentSortMap 主对象排序条件
	 * @param childModel 子集模型查询条件,具体见ChildQueryModel
	 * @param pageSize 从第几条开始查
	 * @param pageNum  每页多少条
	 * @return 返回父对象
	 */
	public <T> SearchResult<T> relationSearch(int pageSize, int pageNum, String indexName, String parentType,
                                              T parentBean, Class<T> clazz, Map<String, String> parentRangeMap, Map<String, String> parentSortMap, String[] parentFileds,
                                              ChildQueryModel childModel);
	public <T> SearchResult<T> relationSearch(int pageSize, int pageNum, String indexName, String parentType,
                                              T parentBean, Class<T> clazz, Map<String, String> parentRangeMap, Map<String, String> parentSortMap, String[] parentFileds,
                                              ChildQueryModel childModel, boolean andOr);
	
	/**
	 * 通用保存文档集合
	 * @param indexName 索引名称
	 * @param type 映射类型
	 * @param t 对象
	 */
	public <T> void saveDoc(String indexName, String type, T t);
	
	/**
	 * 通用批量创建需要所以的文档集合
	 * @param indexName 索引名称
	 * @param type 映射类型
	 * @param ts 对象实例集合
	 */
	public <T> void batchSaveDocs(String indexName, String type, List<T> ts);
	
	/**
	 * 通用保存子文档
	 * @param indexName 索引名称
	 * @param childType 子映射类型
	 * @param t 子对象
	 * @param parentId 父ID
	 */
	public <T> void saveChildDoc(String indexName, String childType, T t, String parentId);
	
	/**
	 * 通用批量保存子文档集合
	 * @param indexName 索引名称
	 * @param childType 子映射类型
	 * @param ts 子对象实例集合
	 * @param parentId 父ID
	 */
	public <T> void batchSaveChildDocs(String indexName, String childType, List<T> ts, String parentId);
	
	/**
	 * 通用根据主键删除文档
	 * @param indexName
	 * @param type
	 * @param id
	 */
	public void delDoc(String indexName, String type, String id);
	/**
	 * 删除子文档
	 * @param indexName
	 * @param type
	 * @param parentId
	 * @param id
	 */
	public void delSubDoc(String indexName, String type, String parentId, String id); 
	
}
package com.lty.dispatch.framework.elasticsearch.impl;

import com.lty.dispatch.framework.elasticsearch.SearchService;
import com.lty.dispatch.framework.elasticsearch.entity.ChildQueryModel;
import com.lty.dispatch.framework.elasticsearch.entity.GroupResult;
import com.lty.dispatch.framework.elasticsearch.entity.SearchResult;
import com.lty.dispatch.framework.elasticsearch.server.ESServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;

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


/**
 * 全文检索具体实现类
 * @author pc
 *
 */
@Service("searchService")
@ConditionalOnBean(ESServer.class)
public class SearchServiceImpl implements SearchService {

	@Autowired
	private ESServer esServer;
	@Override
	public <T> SearchResult<T> search(int pageSize, int pageNum, String[] indexName,
									  String type, T t, Class<T> clazz, Map<String,String> rangeMap,
									  Map<String,String> sortMap, boolean highLight) {
		return esServer.query(indexName, type, t, clazz, rangeMap, highLight, sortMap, pageSize, pageNum,null);
	}
	
	@Override
	public <T> T searchById(String indexName, String type, Class<T> clazz,
			String id, String value) {
		return esServer.queryById(indexName, type, clazz, id, value);
	}

	@Override
	public <T> SearchResult<T> relationSearch(int pageSize, int pageNum, String indexName, String parentType, 
			T parentBean,Class<T> clazz, Map<String,String> parentRangeMap, Map<String, String> parentSortMap,String[]parentFileds,
			ChildQueryModel childModel) {
		return relationSearch(pageSize,pageNum,indexName,
				parentType,parentBean,clazz,parentRangeMap,parentSortMap,parentFileds,childModel,true);
	}

	@Override
	public <T> void saveDoc(String indexName, String type, T t) {
		esServer.createDocument(indexName, type, t);
		
	}

	@Override
	public <T> void batchSaveDocs(String indexName, String type, List<T> ts) {
		esServer.batchCreateDocument(indexName, type, ts);
		
	}

	@Override
	public <T> void saveChildDoc(String indexName, String childType, T t,
			String parentId) {
		esServer.createChildDocument(indexName, childType, parentId, t);
	}

	@Override
	public <T> void batchSaveChildDocs(String indexName, String childType,
			List<T> ts, String parentId) {
		esServer.batchCreateChildDocument(indexName, childType, parentId, ts);
	}

	@Override
	public void delDoc(String indexName, String type, String id) {
		esServer.deleteDoc(indexName, type, id);
	}

	@Override
	public void delSubDoc(String indexName, String type, String parentId,
			String id) {
		esServer.deleteDocChild(indexName, type, parentId,id);
	}

	@Override
	public <T> SearchResult<T> relationSearch(int pageSize, int pageNum, String indexName, String parentType, 
			T parentBean,Class<T> clazz, Map<String,String> parentRangeMap, Map<String, String> parentSortMap,String[]parentFileds,
			ChildQueryModel childModel, boolean andOr) {
		return esServer.queryRelationParent(indexName, parentType, parentBean, clazz, parentRangeMap, 
				parentSortMap, parentFileds,childModel, andOr,pageSize, pageNum);
	}

	@Override
	public <T> long count(String indexName, String type, T t, Class<T> clazz,
			Map<String, String> rangeMap) {
		return esServer.count(indexName, type, t, clazz, rangeMap);
	}

	@Override
	public <T> List<GroupResult> groupSearch(String indexName, String type,
											 T t, Map<String, String> rangeMap, String groupName) {
		return esServer.groupBy(indexName, type, t, rangeMap, groupName);
	}

}

java代码应用

public Page<DispatchInoutYardLog> queryEs(InoutYardLogSearchDto condition , UserInfo userInfo) {
        Integer pageNum = condition.getPageSize();
        Integer pageSize = condition.getCurrentPage() - 1;
        String yardIndex = EsConstant.INOUT_YARD_INDEX;

        //设置索引,如果跨月查询,则会查询多个索引
        Set<String> set = new HashSet<>();

        //范围参数拼凑 计划时间 发生时间
        Map<String, String> rangeMap = new HashMap<>();
        if (condition.getPlanTimeStart() != null && condition.getPlanTimeEnd() != null) {
            set.add(String.format(yardIndex, DateUtils.formatToStr(condition.getPlanTimeStart(), "yyyy-MM")));
            set.add(String.format(yardIndex, DateUtils.formatToStr(condition.getPlanTimeEnd(), "yyyy-MM")));
            rangeMap.put("startTime", "between:"+condition.getPlanTimeStart().getTime()/1000+","+condition.getPlanTimeEnd().getTime()/1000);
        }

        if (condition.getInTime() != null && condition.getOutTime() != null) {
            set.add(String.format(yardIndex, DateUtils.formatToStr(condition.getInTime(), "yyyy-MM")));
            set.add(String.format(yardIndex, DateUtils.formatToStr(condition.getOutTime(), "yyyy-MM")));
            rangeMap.put("inoutTime", "between:"+condition.getInTime().getTime()/1000+","+condition.getOutTime().getTime()/1000);
        }
        String[] indexName = set.toArray(new String[0]);

        DispatchInoutYardLog yardLog = new DispatchInoutYardLog();
        if(StringUtils.isNotBlank(condition.getPlanId())){
            yardLog.setPlanId(condition.getPlanId());
        }

        if (null != condition.getDirection()) {
            yardLog.setDirection(condition.getDirection());
        }
        if (StringUtils.isNotBlank(condition.getDriverName())) {
            yardLog.setDriverName(condition.getDriverName());
        }
      
        //多个线路查询
        List<String> allUserLines = userInfo.getAllUserLines();
        if (CollectionUtils.isNotEmpty(allUserLines)) {
            if ((StringUtils.isNotEmpty(condition.getLineCode()) && allUserLines.contains(condition.getLineCode())) ) {
                yardLog.setLineCode(condition.getLineCode());
            }else if( allUserLines.size() == 1){
                yardLog.setLineCode(allUserLines.get(0));
            } else {
                StringBuilder sb = new StringBuilder();
                sb.append("or");
                allUserLines.stream().forEach(t -> {
                    sb.append(":").append(t).append(" ");
                });
                yardLog.setLineCode(sb.toString());
            }
        } else {
            return new Page<DispatchInoutYardLog>();
        }


        Map<String,String> sortMap = new HashMap<>();
        sortMap.put("inoutTime", "desc");

        SearchResult<DispatchInoutYardLog> search = null;
        try {
            search = searchService.search(pageSize, pageNum, indexName, EsConstant.INOUT_YARD_TYPE, yardLog, DispatchInoutYardLog.class, rangeMap, sortMap, false);
        } catch (Exception e) {
            return new Page<>();
        }
        Page<DispatchInoutYardLog> page = new Page(condition.getCurrentPage(), condition.getPageSize());
        page.setPages(pageNum);
        page.setRecords(search.getRets());
        page.setTotal((search.getNumFound()));
        return page;
    }

 

具体的代码请看https://download.csdn.net/download/mxlgslcd/12628788

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值