黑马旅游案例es

 

目录

普通过滤 

BoolQuery组合条件查询,多条件过滤 

附近酒店功能 

广告置顶功能

 代码


普通过滤 

黑马旅游案例es_第1张图片

BoolQuery组合条件查询,多条件过滤 

多条件过滤我们用BoolQuery,下一级可以用must,not_must,filter精确查询我们用term,价格price查询时范围查询,我们用range

黑马旅游案例es_第2张图片

黑马旅游案例es_第3张图片  

附近酒店功能 

黑马旅游案例es_第4张图片

黑马旅游案例es_第5张图片

 要取得sort值,级别与_source等级一样;

 黑马旅游案例es_第6张图片

广告置顶功能

增加权重 ,在基本条件下(我们这里直接用前面的多条件过滤),加一个functions打分函数

黑马旅游案例es_第7张图片

 黑马旅游案例es_第8张图片

 代码

package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class HotelService extends ServiceImpl implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) throws IOException {
        /*1.准备request*/
        SearchRequest request = new SearchRequest("hotel");

        /*2.构建query:多条件过滤*/
        extracted(params, request);

        /*3.分頁*/
        Integer page = params.getPage();
        Integer size = params.getSize();
        request.source().from((page - 1) * size).size(size);

        /**
         * 距离排序功能
         * 比较复杂可以在sort()里面+SortBuilder
         * 比如我们这的sort需要以距离排序,还有单位,排序方式
         */
        String location = params.getLocation();
        if (location != null && !location.equals("")) {
            request.source().
                    sort(SortBuilders.geoDistanceSort("location", new GeoPoint(location))
                            .order(SortOrder.ASC)
                            .unit(DistanceUnit.KILOMETERS));
        }


        /*4.发送请求*/
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        /*5.解析响应*/
        return handleResponse(response);
    }


    /**
     * 辅助
     *
     * @param params
     */
    private void extracted(RequestParams params, SearchRequest request) {
        /**
         * 辅助字段查询:城市、品牌、酒店星级
         */
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        /*关键字搜索*/
        if ((params.getKey()) == null || "".equals(params.getKey())) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("name", params.getKey()));
        }

        /*城市条件*/
        if (params.getCity() != null && !params.getCity().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));
        }

        /*品牌条件*/
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }

        /*星级条件*/
        if (params.getStarName() != null && !params.getStarName().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("startName", params.getStarName()));
        }

        /*价格*/
        if (params.getMiniPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMiniPrice()).lte(params.getMaxPrice()));
        }

        /**
         * 算分控制
         */
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                //1.基本查询:前面条件查询的内容进行重新打分
                boolQuery,
                //2.打分数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //3.其中一个打分
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //过滤条件
                                QueryBuilders.termQuery("isAD", true),
//                               算分函数
                                ScoreFunctionBuilders.weightFactorFunction(5)
                        )
                }
        );

        request.source().query(functionScoreQueryBuilder);
    }


    /**
     * 解析响应
     *
     * @param response:响应
     */
    private PageResult handleResponse(SearchResponse response) {
        List list = new ArrayList<>();
        PageResult pageResult = new PageResult();

        /*1.解析响应*/
        SearchHits searchHits = response.getHits();

        /*2.得到数据总数*/
        long total = searchHits.getTotalHits().value;
        System.out.println("共搜到" + total + "条数据");

        /*3.得到文档数组*/
        SearchHit[] hits = searchHits.getHits();

        /*4.遍历文档数组,取出每条数据中的_source*/
        for (SearchHit hit : hits) {
            String source = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(source, HotelDoc.class);

            //从文档中取出排序值,等级与source一致,是数组是因为可能有多个值决定排序
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0) {
                Object sortValue = sortValues[0];
                //设置距离
                hotelDoc.setDistance(sortValue);
            }
            list.add(hotelDoc);
        }

        /*将结果封装到PageResult中*/
        pageResult.setHotels(list);
        pageResult.setTotal(total);

        return pageResult;
    }
}

你可能感兴趣的:(elasticsearch,java,elasticsearch,搜索引擎)