黑马旅游案例es

文章目录

  • 1、 普通过滤
  • 2、BoolQuery组合条件查询,多条件过滤
  • 3、附近酒店功能
  • 4、广告置顶功能
  • 5、实战代码

1、 普通过滤

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

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

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

3、附近酒店功能

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

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

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

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

4、广告置顶功能

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

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

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

5、实战代码

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.commons.lang3.StringUtils;
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.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
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 org.springframework.util.CollectionUtils;

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

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;


    @Override
    public PageResult search(RequestParams params) {
        try {
            //1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            buildBasicQuery(params, request);

            //2.2分页
            int page = params.getPage();
            int size = params.getSize();

            request.source().from((page-1)*size).size(size);

            //2.3排序
            String location = params.getLocation();
            if (StringUtils.isNotBlank(location)){
                request.source().sort(SortBuilders.geoDistanceSort("location",new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS)
                );
            }


            //3.发送请求,得到响应
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //4.解析响应

            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        //2.准备DSL
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字搜索
        //2.1全文检索
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)){
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        // 1.2.品牌
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        // 1.3.城市
        String city = params.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQuery.filter(QueryBuilders.termQuery("city", city));
        }
        // 1.4.星级
        String starName = params.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            boolQuery.filter(QueryBuilders.termQuery("starName", starName));
        }
        // 1.5.价格范围
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            maxPrice = maxPrice == 0 ? Integer.MAX_VALUE : maxPrice;
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
        }
         /**
         * 算分控制
         */
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                //1.基本查询:前面条件查询的内容进行重新打分
                boolQuery,
                //2.打分数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //3.其中一个打分
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //过滤条件
                                QueryBuilders.termQuery("isAD", true),
//                               算分函数
                                ScoreFunctionBuilders.weightFactorFunction(5)
                        )
                }
        );

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

     /**
     * 解析响应
     *
     * @param response:响应
     */
    private PageResult handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();

        List<HotelDoc> hotels = new ArrayList<>();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length >0 ){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            hotels.add(hotelDoc);
        }

        System.out.println("总酒店数据共有 :" + total);
        System.out.println("酒店信息 :" + hotels);
        return new PageResult(total,hotels);
    }
}

其中 :

黑马旅游案例es_第9张图片
黑马旅游案例es_第10张图片
黑马旅游案例es_第11张图片

三者为重点

你可能感兴趣的:(elasticsearch,java,数据库)