从ElasticSearch中查询课程信息。
接口信息如下
查询DTO
SearchCourseParamDTO
@Data @ToString public class SearchCourseParamDTO {
private String keywords;
private String mt;
private String st; private String grade;
}
|
视图VO
SearchPageResultVO@Data @ToString public class SearchPageResultVO<T> extends PageResult {
List<String> mtList; List<String> stList;
public SearchPageResultVO(List<T> items, long counts, long page, long pageSize) { super(items, counts, page, pageSize); } }
|
定义Service
新建CourseSearchService
接口,定义课程搜索接口
CourseSearchService
public interface CourseSearchService {
SearchPageResultVO<CourseIndex> queryCoursePubIndex(PageParam pageParam, SearchCourseParamDTO dto); }
|
实现该方法,创建其实现类CourseSearchServiceImpl
CourseSearchServiceImpl@Slf4j @Service @RefreshScope public class CourseSearchServiceImpl implements CourseSearchService {
@Value("${elasticsearch.course.index}") private String courseIndexStore;
@Value("${elasticsearch.course.source-fields}") private String sourceFields;
private final RestHighLevelClient restHighLevelClient;
public CourseSearchServiceImpl(RestHighLevelClient restHighLevelClient) { this.restHighLevelClient = restHighLevelClient; }
@Override public SearchPageResultVO<CourseIndex> queryCoursePubIndex(PageParam pageParam, SearchCourseParamDTO dto) { SearchRequest request = new SearchRequest(courseIndexStore);
SearchSourceBuilder builder = new SearchSourceBuilder(); BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
String[] sourceFieldsArray = sourceFields.split(","); builder.fetchSource(sourceFieldsArray, new String[]{}); if (dto == null) { dto = new SearchCourseParamDTO(); }
if (StringUtils.hasText(dto.getKeywords())) { MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(dto.getKeywords(), "name", "description"); multiMatchQueryBuilder.minimumShouldMatch("70%"); multiMatchQueryBuilder.field("name", 10); boolQuery.must(multiMatchQueryBuilder); } if (StringUtils.hasText(dto.getMt())) { boolQuery.filter(QueryBuilders.termQuery("mtName", dto.getMt())); } if (StringUtils.hasText(dto.getSt())) { boolQuery.filter(QueryBuilders.termQuery("stName", dto.getSt())); } if (StringUtils.hasText(dto.getGrade())) { boolQuery.filter(QueryBuilders.termQuery("grade", dto.getGrade())); } Long pageNo = pageParam.getPageNo(); Long pageSize = pageParam.getPageSize(); int start = (int) ((pageNo - 1) * pageSize); builder.from(start).size(Math.toIntExact(pageSize)); builder.query(boolQuery); builder.highlighter(new HighlightBuilder() .field("name") .preTags("<font style='color:red;font-size:inherit;'>") .postTags("</font>")); request.source(builder); buildAggregation(request); SearchResponse searchResponse = null; try { searchResponse = restHighLevelClient.search(request, RequestOptions.DEFAULT); } catch (IOException e) { log.error("课程搜索异常:", e); return new SearchPageResultVO<CourseIndex>(new ArrayList<CourseIndex>(), 0, 0, 0); }
SearchHits hits = searchResponse.getHits(); SearchHit[] searchHits = hits.getHits(); TotalHits totalHits = hits.getTotalHits(); List<CourseIndex> list = new ArrayList<>();
for (SearchHit hit : searchHits) { String sourceAsString = hit.getSourceAsString(); CourseIndex courseIndex = JSON.parseObject(sourceAsString, CourseIndex.class); Long id = courseIndex.getId(); String name = courseIndex.getName(); Map<String, HighlightField> highlightFields = hit.getHighlightFields(); if (highlightFields != null) { HighlightField nameField = highlightFields.get("name"); if (nameField != null) { Text[] names = nameField.getFragments(); StringBuilder stringBuffer = new StringBuilder(); for (Text str : names) { stringBuffer.append(str.string()); } name = stringBuffer.toString(); } } courseIndex.setId(id); courseIndex.setName(name); list.add(courseIndex); } SearchPageResultVO<CourseIndex> pageResult = new SearchPageResultVO<>(list, totalHits.value, pageNo, pageSize); List<String> mtList= getAggregation(searchResponse.getAggregations(), "mtAgg"); List<String> stList = getAggregation(searchResponse.getAggregations(), "stAgg"); pageResult.setMtList(mtList); pageResult.setStList(stList);
return pageResult; }
private void buildAggregation(SearchRequest request) { request.source().aggregation(AggregationBuilders .terms("mtAgg") .field("mtName") .size(100) ); request.source().aggregation(AggregationBuilders .terms("stAgg") .field("stName") .size(100) ); }
private List<String> getAggregation(Aggregations aggregations, String aggName) { Terms brandTerms = aggregations.get(aggName); List<? extends Terms.Bucket> buckets = brandTerms.getBuckets(); List<String> brandList = new ArrayList<>(); for (Terms.Bucket bucket : buckets) { String key = bucket.getKeyAsString(); brandList.add(key); } return brandList; } }
|
定义Controller
CourseSearchController
@Api(value = "课程搜索接口", tags = "课程搜索接口") @RestController @RequestMapping("/course") public class CourseSearchController {
private final CourseSearchService courseSearchService;
public CourseSearchController(CourseSearchService courseSearchService) { this.courseSearchService = courseSearchService; } @ApiOperation("课程搜索列表") @GetMapping("/list") public SearchPageResultVO<CourseIndex> list(PageParam pageParam, SearchCourseParamDTO searchCourseParamDTO) { return courseSearchService.queryCoursePubIndex(pageParam, searchCourseParamDTO); } }
|