elasticsearch-填坑

1、分页参数 ,start=(page-1)*size

2、高亮字段结果的处理方式

3、float类型参数从map中取出用double接收

4、结果封装需手动封装

package com.search.service;

import java.util.ArrayList;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder.Field;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xuecheng.framework.domain.course.CoursePub;
import com.xuecheng.framework.domain.search.CourseSearchParam;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.framework.resultCode.EsCode;
import com.xuecheng.framework.resultCode.common.CommonCode;
import com.xuecheng.search.config.EsConfig;

@Service
public class EsCourseService {

    @Autowired
    private EsConfig config;
    @Autowired
    private RestHighLevelClient client;

    public ResponseResult list(int page,int size,CourseSearchParam params){
        if(params==null){
            ExceptionCast.cast(CommonCode.NULL_PARAM);
        }
        //关键字查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(StringUtils.isNotBlank(params.getKeyword())){
            MultiMatchQueryBuilder multiMatchQuery = QueryBuilders.multiMatchQuery(params.getKeyword(), "name","teachplan","descripe")
                                                                  .minimumShouldMatch("70%")
                                                                  .field("name", 10);
            boolQuery.must(multiMatchQuery);
        }
        //一节分类
        if(StringUtils.isNotBlank(params.getMt())){
            boolQuery.filter(QueryBuilders.termQuery("mt", params.getMt()));            
        }
        //二级分类
        if(StringUtils.isNotBlank(params.getSt())){
            boolQuery.filter(QueryBuilders.termQuery("st", params.getSt()));
        }
        //课程难度
        if(StringUtils.isNotBlank(params.getGrade())){
            boolQuery.filter(QueryBuilders.termQuery("grade", params.getGrade()));
        }
        //高亮
        HighlightBuilder hlb = new HighlightBuilder();
        hlb.preTags("<font class='esClass'>")
           .postTags("</font>")
           .fields().add(new Field("name"));//设置name高亮
        
        SearchSourceBuilder ssb = new SearchSourceBuilder();
        if(config.getSourceFields()==null){
            ExceptionCast.cast(EsCode.READ_CONFIG_PARAM_FAIL);
        }
        if(page<=0){
            page=1;
        }
        if(size<=0){
            size=20;
        }
        ssb.fetchSource(config.getSourceFields().toArray(new String[]{}), new String[]{})
           .from((page-1)*size)  //start计算细节需要注意
           .size(size)
           .query(boolQuery)
           .highlighter(hlb);
        //sr
        SearchRequest sr = new SearchRequest(config.getIndex());
        sr.types(config.getType());
        sr.source(ssb);
        SearchResponse response = null;
        try {
            response = client.search(sr);
        } catch (Exception e) {
            return new ResponseResult(CommonCode.SUCCESS);
        }
        SearchHits hits = response.getHits();
        ArrayList<CoursePub> list = new ArrayList<CoursePub>();
        for(SearchHit hit:hits){
            CoursePub coursePub = new CoursePub();
            //1、设置name
            Map<String, Object> map = hit.getSourceAsMap();
            //取出名称
            String name = (String)map.get("name");
            //取出高亮字段
            Map<String, HighlightField> highLighfields = hit.getHighlightFields();
            if(highLighfields!=null){
                HighlightField nameField = highLighfields.get("name");
                if(nameField!=null){
                    Text[] fragments = nameField.getFragments();
                    StringBuffer stringBuffer = new StringBuffer();
                    for(Text fragment:fragments){
                        stringBuffer.append(fragment.string());
                    }
                    name = stringBuffer.toString();
                }
            }
            coursePub.setName(name);
            
            //2、设置pic
            String pic = (String)map.get("pic");
            coursePub.setPic(pic);
            
            //3、价格
            Double price = (Double)map.get("price");
            coursePub.setPrice(price);
            
            //4、原价
            Double old_price = (Double)map.get("old_price");
            coursePub.setPriceOld(old_price);
            list.add(coursePub);
        }
        QueryResult<CoursePub> qr = new QueryResult<>();
        qr.setList(list);
        qr.setTotal(hits.getTotalHits());
        return new QueryResponseResult<>(CommonCode.SUCCESS, qr);
    }
}

 

转载于:https://www.cnblogs.com/dehigher/p/10181028.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值