主页:写程序的小王叔叔的博客欢迎来访👀
支持:点赞收藏关注
一、BBoss-ES操作数据
1、pom.xml
<dependency><groupId>com.bbossgroups.plugins</groupId><artifactId>bboss-elasticsearch-spring-boot-starter</artifactId><version>6.0.0</version><exclusions><exclusion><artifactId>slf4j-log4j12</artifactId><groupId>org.slf4j</groupId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId><version>${elasticsearch.version}</version></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>${elasticsearch.version}</version></dependency>
2、基本配置
elasticsearch: host: 10.1*.**.** port: 9200 bboss: default: name: default elasticPassword: elastic elasticUser: elastic elasticsearch: dateFormat: yyyy.MM.dd discoverHost: false rest: hostNames: 1*.**.**.**:9200 scrollBlockedWaitTimeout: 0 scrollThreadCount: 200 scrollThreadQueue: 200 showTemplate: true sliceScrollBlockedWaitTimeout: 0 sliceScrollThreadCount: 100 sliceScrollThreadQueue: 100 timeZone: Asia/Shanghai http: connectionRequestTimeout: 5000 customHttpRequestRetryHandler: org.frameworkset.spi.remote.http.ConnectionResetHttpRequestRetryHandler defaultMaxPerRoute: 200 hostnameVerifier: '' keyPassword: '' keystore: '' maxHeaderCount: 200 maxLineLength: -1 maxTotal: 400 retryTime: 1 staleConnectionCheckEnabled: false timeoutConnection: 5000 timeoutSocket: 5000 validateAfterInactivity: 2000 dslfile: refreshInterval: -1
3、结构配置
3.1 配置ESSTartConfigurer
importorg.frameworkset.elasticsearch.boot.BBossESStarter; importorg.springframework.boot.context.properties.ConfigurationProperties; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.context.annotation.Primary; publicclassESSTartConfigurer { initMethod="start") ("spring.elasticsearch.bboss.default") (publicBBossESStarterbbossESStarter(){ returnnewBBossESStarter(); } }
3.2配置EsQueryToolsConfig
importcom.alibaba.fastjson.JSONObject; importorg.frameworkset.elasticsearch.boot.BBossESStarter; importorg.frameworkset.elasticsearch.client.ClientInterface; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.stereotype.Component; publicclassEsQueryToolsConfig { privateBBossESStarterbbossESStarterDefault; /*** 用sql查询* @param sql* @return*/publicStringqueryForSQL(Stringsql){ ClientInterfaceclientUtil=bbossESStarterDefault.getRestClient(); JSONObjectjsonObject=newJSONObject(); jsonObject.put("sql",sql); StringrtnJson=clientUtil.executeHttp("/_sql/", jsonObject.toJSONString(), ClientInterface.HTTP_POST); returnrtnJson; } /*** 用原生的 es的dsl查询* @param indexName* @param dsl* @return*/publicStringqueryForDSL(StringindexName,Stringdsl) { ClientInterfaceclientUtil=bbossESStarterDefault.getRestClient(); StringrtnJson=clientUtil.executeHttp("/"+indexName+"/_search", dsl, ClientInterface.HTTP_POST); returnrtnJson; } }
4、CRUD
在业务接口 **impl 中,实现基本业务逻辑。
代码块代表当前业务逻辑,具体问题具体分析。
publicclassTeacherResourceServiceImplimplementsTeacherResourceService { privateTeacherResourceDaoteacherResourceDao; privateElasticsearchRestTemplateelasticsearchRestTemplate; publicPageInfo<TeacherResourceVO>findTeacherResourceFromES(T*****TOt***TO) throwsException{ Listt*******OsList=newArrayList(); PageInfo<T******O>teacherResPages=newPageInfo<>(); if (elasticsearchRestTemplate.indexExists("s*******n")){ //聚合获取学校id-教师id的相关信息StringteacherResJson=teacherResourceDao.findTeacherResourceList(t*******TO) ; JSONObjectbuildTeacherObj=JSONObject.parseObject(teacherResJson); JSONArraybuildTeacherArr=buildTeacherObj.getJSONObject("aggregations").getJSONObject("b*******_id").getJSONArray("buckets"); for (inti=0; i<buildTeacherArr.size(); i++) { TeacherResourceVOteacherResourceVO=newTeacherResourceVO(); JSONObjectteacherObj=buildTeacherArr.getJSONObject(i); if (null!=teacherObj) { StringteacherId=teacherObj.getString("key"); StringteacherNameJson=teacherResourceDao.getUserNameFromES(teacherId); JSONObjectteacherNameObj=JSONObject.parseObject(teacherNameJson); StringteacherName=teacherNameObj.getJSONObject("hits").getJSONArray("hits").getJSONObject(0).getJSONObject("_source").getString("user_name"); JSONObjectschoolNameObj=JSONObject.parseObject(schoolNameJson); StringschoolName=schoolNameObj.getJSONObject("hits").getJSONArray("hits").getJSONObject(0).getJSONObject("_source").getString("organization_name"); teacherResourceVO.setTeacherId(teacherId); teacherResourceVO.setTeacherName(teacherName); teacherResourceVO.setRecourceAccount(Integer.parseInt(teacherResCount)); teacherResourceVOsList.add(teacherResourceVO); } } IntegertotalNum=teacherResourceVOsList.size(); intpageNum=teacherResourceDTO.getPageNum(); intpageSize=teacherResourceDTO.getPageSize(); IntegertotalPage=0; if (totalNum>0) { totalPage=totalNum%pageSize==0?totalNum/pageSize : totalNum/pageSize+1; } if (pageNum>totalPage) { pageNum=totalPage; } intstartPoint= (pageNum-1) *pageSize; intendPoint=startPoint+pageSize; if (totalNum<=endPoint) { endPoint=totalNum; } ListPageList=newArrayList(); PageList=t******OsList.subList(startPoint, endPoint); teacherResPages.setPageNum(t*****TO.getPageNum()); teacherResPages.setPageSize(t*******O.getPageSize()); teacherResPages.setTotal(t******sList.size()); teacherResPages.setPages(totalPage ); teacherResPages.setList(PageList); returnteacherResPages; } returnteacherResPages; } }
在dao层 引入文件【见上】:
privateEsQueryToolsConfigesQueryToolsConfig; /**** 获取学校教师资源数量* @param teacherResourceDTO* @return* @throws Exception*/publicStringfindTeacherResourceList(T*******O*****O) throwsException{ SimpleDateFormatsimpleDateFormat=newSimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //基础sqlStringselect_sql="select base_user_id , count(*) as teacherResCount from s*******n "; Stringwhere_sql="where 1=1 "; StringgroupBy_sql="group by base_user_id "; Stringorder_sql=" order by teacherResCount desc limit 10"; if(StringUtils.isNotBlank(t********O.getSchoolId())){ where_sql=where_sql.concat(" and b******_id = '"+t*******O.getSchoolId() +"' "); } if (StringUtils.isNotBlank(te*****O.getBeginDate())) { longbeginTime=simpleDateFormat.parse(t*****O.getBeginDate() +LoginConstant.START_TIME).getTime(); where_sql=where_sql.concat( " and create_time >= '"+beginTime+"' "); } if (StringUtils.isNotBlank(t******O.getEndDate())) { longendTime=simpleDateFormat.parse(te********O.getEndDate() +LoginConstant.END_TIME).getTime(); where_sql=where_sql.concat( " and create_time < '"+endTime+"' "); } Stringsql=select_sql+where_sql+groupBy_sql ; StringretJson=this.esQueryToolsConfig.queryForSQL( sql ); System.out.println(sql); returnretJson; }
二、抽ES数据存到List数组
//自定义 学科名称数组ArrayListarraySubList=newArrayList(); ArrayListarraySubIdList=newArrayList(); if (elasticsearchRestTemplate.indexExists("s*******************b")) { SearchQuerysearchQuery=newNativeSearchQueryBuilder() .withIndices("s************b") .withTypes("_***************") .withQuery(boolQuery) .build(); //统计学生的发布课程信息List<St***************O>s*************Os=elasticsearchRestTemplate.queryForList(searchQuery, S*************O.class); //根据学生发布课程编号获取学段,学科基本信息for (inti=0; i<stuIssueD**********s.size(); i++) { StringstrCourseId=stu************s.get(i).getCourse_base_id(); //课程统计BoolQueryBuilderqueryCourseInfo=QueryBuilders.boolQuery(); queryCourseInfo.must(QueryBuilders.termQuery("co******id", strCourseId)); SearchQueryqueryCourse=newNativeSearchQueryBuilder() .withIndices("s****************o") .withTypes("_d************************") .withQuery(queryCourseInfo) .build(); List<Co******O>co*************List=elasticsearchRestTemplate.queryForList(queryCourse, C***********O.class); for (intj=0; j<co**********ist.size(); j++) { BoolQueryBuilderquerySubInfo=QueryBuilders.boolQuery(); //学段信息if (StringUtils.isNotBlank(subjectId)) { querySubInfo.must(QueryBuilders.termQuery("s******de", subjectId)); } else { querySubInfo.must(QueryBuilders.termQuery("s***********de", courseVOFromESList.get(j).getBusiness_subject_id())); } //学科信息if (StringUtils.isNotBlank(stageId)) { querySubInfo.must(QueryBuilders.termQuery("s******de", stageId)); } else { querySubInfo.must(QueryBuilders.termQuery("s*******de", courseVOFromESList.get(j).getBu*******_id())); } SearchQueryquerySubjectInfo=newNativeSearchQueryBuilder() .withIndices("st*********t") .withTypes("_***********c") .withQuery(querySubInfo) .build(); List<Su***********O>subList=elasticsearchRestTemplate.queryForList(querySubjectInfo, Su*********O.class); //动态添加 - list数组//动态添加 - list数组arraySubList.add(subList.get(0).getSubject_name()); arraySubIdList.add(subList.get(0).getSubject_code()); } } List<St**********O>s**************List=homeworkService.getQuestionAndknowledgeTotal(s****************O); for (inti=0; i<st************List.size(); i++) { //学生学习的课程数量st**************List.get(i).setResourceAccount(s************s.size()); stud**************List.get(i).setSubjectId(subjectId); //学科名称subList.stream().map(S*******::getSubject_name).collect(Collectors.toList()); // studentSubResourceVOList.get(i).setSubjectName(subName.toString()); } returnstudentSubResourceVOs; }
转载声明:本文为博主原创文章,未经博主允许不得转载
⚠️注意 ~
💯本期内容就结束了,如果内容有误,麻烦大家评论区指出!
如有疑问❓可以在评论区留言💬或私信留言💬,尽我最大能力🏃♀️帮大家解决👨🏫!
如果我的文章有帮助到您,欢迎点赞+关注✔️鼓励博主🏃,您的鼓励是我分享的动力🏃🏃🏃~