ES仿京东搜索


1、依赖

 <!--解析网页-->
<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.10.2</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.75</version>
</dependency>


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    <!--        自定义es版本依赖  否则会出bug-->
    <version>7.6.1</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

2、后端

(1)配置类

//集成es 配置
@Configuration
public class ESConfig {

    @Bean
    public RestHighLevelClient client(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")
                ));
        return client;
    }
}

(2)实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Content {
    //商品标题
    private String title;
    //商品的图片
    private String img;
    //商品的价格
    private String price;
}

(3)爬取数据工具类

当前京东首页数据自动跳转到登录页,已无法实现效果,可换一个网站

@Component
public class HtmlParseUtil {
    public List<Content> goods(String keyword) throws IOException {
        //获取请求
        String url= "https://search.jd.com/Search?keyword="+keyword+"&enc=utf-8";
        //解析网页
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        //获取所有的li元素
        Elements li = element.getElementsByTag("li");

        ArrayList<Content> goodsList = new ArrayList<>();

        for (Element el : li) {
            //获取每一个li标签下所有的img标签下的第一个元素,属性为src
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            //获取每一个li标签下所有的p-price标签下的第一个元素,并转换为文档
            String price = el.getElementsByClass("p-price").eq(0).text();

            String title = el.getElementsByClass("p-name").eq(0).text();

            // 封装获取的数据
            Content content = new Content();
            content.setTitle(title);
            content.setImg(img);
            content.setPrice(price);
            //将封装的好的对象放入list集合
            goodsList.add(content);
        }
        return goodsList;
    }
}

(4)service

@Service
public class ContentService {

    @Resource
    private RestHighLevelClient client;


    public Boolean parseContent(String keywords) throws IOException {
        //获取爬取的数据
        List<Content> contentList = new HtmlParseUtil().goods(keywords);

        //创建批量请求
        BulkRequest bulkRequest = new BulkRequest();
        //设置超时时间
        bulkRequest.timeout("100s");

        //通过for循环依次插入
        for (int i = 0; i < contentList.size(); i++) {
            bulkRequest.add(
                    new IndexRequest("jd_goods")
                            .source(JSON.toJSONString(contentList.get(i)), XContentType.JSON)
            );
        }
        // 通过客户端发送请求
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        // 获得状态码
        return !bulk.hasFailures();
    }

    public List<Map<String,Object>> goodsHighLight(String keyword,int pageNo,int pageSize) throws IOException {

        SearchRequest searchRequest = new SearchRequest("jd_goods");
        //构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        //精准查询
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        //查询器
        sourceBuilder.query(termQueryBuilder);
        //设置超时时间
        sourceBuilder.timeout(new TimeValue(160, TimeUnit.SECONDS));


        //设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        //设置高亮的字段
        highlightBuilder.field("title");
        highlightBuilder.requireFieldMatch(false); //是否多个高亮显示
        //高亮的样式
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        //将高亮设置放入构建器中
        sourceBuilder.highlighter(highlightBuilder);

        //执行搜索
        searchRequest.source(sourceBuilder);
        //客户端发送请求
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);

        ArrayList<Map<String,Object>> list = new ArrayList<>();
        //将所有符合条件的循环输出
        for (SearchHit hit : search.getHits().getHits()) {
            //取出高亮集合
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            //取出高亮中key值为title的
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //如果高亮字段不为空 ,就将原来的字段替换为高亮字段
            if (title!=null){
                Text[] fragments = title.fragments();
                String n_title="";
                for (Text fragment : fragments) {
                    n_title+=fragment;
                }
                sourceAsMap.put("title",n_title); //高亮字段替换原来的内容即可
            }
            list.add(sourceAsMap);
        }
        return list;
    }
}

(5)controller

@Controller
public class IndexController {
    @GetMapping("/")
    public String index(){
        return "index";
    }
}
@RestController
public class ContentController {

    @Autowired
    ContentService service;

    @RequestMapping("/goods/{keyword}")
    public Boolean goods(@PathVariable("keyword") String keyword) throws IOException {
        Boolean aBoolean = service.parseContent(keyword);
        return  aBoolean;
    }

    @GetMapping("/page/{keyword}/{pageNo}/{pageSize}")
    public List<Map<String,Object>> page(@PathVariable("keyword") String keyword,
                                         @PathVariable("pageNo") int pageNo,
                                         @PathVariable("pageSize") int pageSize) throws IOException {

        List<Map<String, Object>> goods = service.goodsHighLight(keyword, pageNo, pageSize);
        System.out.println(goods.toString());

        return goods;

    }
}

3、前端

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8"/>
    <title>狂神说Java-ES仿京东实战</title>
    <link rel="stylesheet" th:href="@{/css/style.css}"/>

</head>

<body class="pg">
<div class="page" id="app">
    <div id="mallPage" class=" mallist tmall- page-not-market ">

        <!-- 头部搜索 -->
        <div id="header" class=" header-list-app">
            <div class="headerLayout">
                <div class="headerCon ">
                    <!-- Logo-->
                    <h1 id="mallLogo">
                        <img th:src="@{/images/jdlogo.png}" alt="">
                    </h1>

                    <div class="header-extra">

                        <!--搜索-->
                        <div id="mallSearch" class="mall-search">
                            <form name="searchTop" class="mallSearch-form clearfix">
                                <fieldset>
                                    <legend>天猫搜索</legend>
                                    <div class="mallSearch-input clearfix">
                                        <div class="s-combobox" id="s-combobox-685">
                                            <div class="s-combobox-input-wrap">
                                                <input  v-model="keyword" type="text" autocomplete="off" value="dd" id="mq"
                                                        class="s-combobox-input" aria-haspopup="true">
                                            </div>
                                        </div>
                                        <button type="submit" id="searchbtn" @click.prevent="searchKey">搜索</button>
                                    </div>
                                </fieldset>
                            </form>
                            <ul class="relKeyTop">
                                <li><a>狂神说Java</a></li>
                                <li><a>狂神说前端</a></li>
                                <li><a>狂神说Linux</a></li>
                                <li><a>狂神说大数据</a></li>
                                <li><a>狂神聊理财</a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 商品详情页面 -->
        <div id="content">
            <div class="main">
                <!-- 品牌分类 -->
                <form class="navAttrsForm">
                    <div class="attrs j_NavAttrs" style="display:block">
                        <div class="brandAttr j_nav_brand">
                            <div class="j_Brand attr">
                                <div class="attrKey">
                                    品牌
                                </div>
                                <div class="attrValues">
                                    <ul class="av-collapse row-2">
                                        <li><a href="#"> 狂神说 </a></li>
                                        <li><a href="#"> Java </a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>

                <!-- 排序规则 -->
                <div class="filter clearfix">
                    <a class="fSort fSort-cur">综合<i class="f-ico-arrow-d"></i></a>
                    <a class="fSort">人气<i class="f-ico-arrow-d"></i></a>
                    <a class="fSort">新品<i class="f-ico-arrow-d"></i></a>
                    <a class="fSort">销量<i class="f-ico-arrow-d"></i></a>
                    <a class="fSort">价格<i class="f-ico-triangle-mt"></i><i class="f-ico-triangle-mb"></i></a>
                </div>

                <!-- 商品详情 -->
                <div class="view grid-nosku">

                    <div class="product" v-for="result in results">
                        <div class="product-iWrap">
                            <!--商品封面-->
                            <div class="productImg-wrap">
                                <a class="productImg">
                                    <img :src="result.img">
                                </a>
                            </div>
                            <!--价格-->
                            <p class="productPrice">
                                <em><b>¥</b>{{result.price}}</em>
                            </p>
                            <!--标题-->
                            <p class="productTitle">
                                <a v-html="result.title"> </a>
                            </p>
                            <!-- 店铺名 -->
                            <div class="productShop">
                                <span>店铺: 狂神说Java </span>
                            </div>
                            <!-- 成交信息 -->
                            <p class="productStatus">
                                <span>月成交<em>999笔</em></span>
                                <span>评价 <a>3</a></span>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="../static/js/vue.min.js"></script>
<script src="../static/js/axios.min.js"></script>

<script>
    new Vue({
        el: '#app',
        data: {
            keyword:'',
            results:[]   //返回的结果
        },
        methods: {
            searchKey: function(){
                var a =this.keyword;
                console.log(a);
                axios.get('page/'+a+"/1/30").then(function (response) {
                    console.log(response.data);
                    this.results=response.data;

                    console.log(response.data.title)
                })
            }
        }
    })
</script>
</body>
</html>

4、效果展示

image-20210605000917384


  目录