• (四)ElasticSearch-实战模拟京东搜索


    1.Jsoup获取数据

    • pom
            <!--jsoup-->
            <dependency>
                <groupId>org.jsoup</groupId>
                <artifactId>jsoup</artifactId>
            </dependency>
    
    • HtmlParseUtil
    import com.mine.esjd.pojo.Content;
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.nodes.Element;
    import org.jsoup.select.Elements;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    public class HtmlParseUtil {
    
        public static void main(String[] args) throws Exception {
            parseJD("java").forEach(System.out::println);
        }
    
        /**
         * parseJD
         *
         * @return
         */
        public static List<Content> parseJD(String keyword) {
            List<Content> list = new ArrayList<>();
            String url = "https://search.jd.com/Search?keyword=" + keyword;
            //Document document = Jsoup.parse(new URL(url), 30000);
            Document document = null;
            try {
                document = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 5.1; zh-CN) AppleWebKit/535.12 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/535.12").timeout(30000).get();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (document == null) {
                return list;
            }
            Element element = document.getElementById("J_goodsList");
            Elements elements = element.getElementsByTag("li");
            for (Element el : elements) {
                String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
                String pricce = el.getElementsByClass("p-price").eq(0).text();
                String title = el.getElementsByClass("p-name").eq(0).text();
                list.add(new Content(title, pricce, img));
            }
            return list;
        }
    }
    
    

    2.添加数据至ES

    • pom
            <!-- lombok -->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
            <!-- fastjson -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
            </dependency>
            <!-- elasticsearch -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            </dependency>
            <!--thymeleaf -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <!-- web -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--jsoup-->
            <dependency>
                <groupId>org.jsoup</groupId>
                <artifactId>jsoup</artifactId>
            </dependency>
            <!--hutool-->
            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
            </dependency>
    
    • 配置Bean
    @Configuration
    public class ESConfig {
    
        @Bean
        public RestHighLevelClient restHighLevelClient() {
            return new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
        }
    }
    
    
    • pojo
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Content {
    
        private String title;
        private String price;
        private String img;
    }
    
    • Service
    public interface ContentService {
    
        /**
         * 添加数据至ES
         *
         * @param keyword
         * @return
         */
        public boolean parse(String keyword);
    }
    
    @Service
    public class ContentServiceImpl implements ContentService {
    
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
    
        @Autowired
        private RestHighLevelClient restHighLevelClient;
    
        @Override
        public boolean parse(String keyword) {
            List<Content> contents = HtmlParseUtil.parseJD(keyword);
            BulkRequest request = new BulkRequest();
            request.timeout("30s");
            for (int i = 0; i < contents.size(); i++) {
                request.add(new IndexRequest("jd_goods").id(snowflake.nextIdStr()).source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
            }
            try {
                BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
                return !response.hasFailures();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
    
    }
    
    • Controller
    @RestController
    public class ContentController {
    
        @Autowired
        private ContentService contentService;
    
        @GetMapping("/parse/{keyword}")
        public Boolean parse(@PathVariable("keyword") String keyword) {
            return contentService.parse(keyword);
        }
    }
    
    • 访问http://localhost:9090/parse/{yourword}

    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" @click.prevent="searchKey" id="searchbtn">搜索</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 th:src="@{/js/vue.min.js}"></script>
    <script th:src="@{/js/axios.min.js}"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                keyword: '',
                results: []
            },
            methods: {
                searchKey() {
                    var keyword = this.keyword;
                    console.log(keyword);
                    axios.get('search/' + keyword + '/1/30').then(response=>{
                        this.results=response.data;
                        console.log(this.results);
                    });
                }
            }
        })
    </script>
    
    </body>
    </html>
    
    • Controller
    @RestController
    public class ContentController {
    
        @Autowired
        private ContentService contentService;
    
        @GetMapping("/search/{keyword}/{pageNo}/{pageSize}")
        public List<Map<String, Object>> search(@PathVariable("keyword") String keyword,
                                                @PathVariable("pageNo") Integer pageNo,
                                                @PathVariable("pageSize") Integer pageSize
        ) {
            return contentService.search(keyword, pageNo, pageSize);
        }
    }
    
    • Service
    public interface ContentService {
    
        /**
         * 从ES查询数据
         *
         * @param keyword
         * @param pageNo
         * @param pageSize
         * @return
         */
        public List<Map<String, Object>> search(String keyword, Integer pageNo, Integer pageSize);
    }
    
    @Service
    public class ContentServiceImpl implements ContentService {
    
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
    
        @Autowired
        private RestHighLevelClient restHighLevelClient;
    
        @Override
        public List<Map<String, Object>> search(String keyword, Integer pageNo, Integer pageSize) {
            List<Map<String, Object>> list = new ArrayList<>();
            SearchRequest searchRequest = new SearchRequest("jd_goods");
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            //分页
            sourceBuilder.from((pageNo - 1) * pageSize);
            sourceBuilder.size(pageSize);
    
            //精准查询
            //TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
    
            //match查询
            MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("title", keyword);
            sourceBuilder.query(matchQueryBuilder);
            sourceBuilder.timeout(TimeValue.timeValueSeconds(30));
    
            //高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.preTags("<span style='color:red'>");
            highlightBuilder.postTags("</span>");
            highlightBuilder.field("title");
            sourceBuilder.highlighter(highlightBuilder);
            //执行搜索
            searchRequest.source(sourceBuilder);
            try {
                SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
                for (SearchHit searchHit : searchResponse.getHits().getHits()) {
                    //高亮置换
                    Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
                    Text[] fragments = highlightFields.get("title").fragments();
                    String highlightTitle = "";
                    if (null != fragments && fragments.length > 0) {
                        for (int i = 0; i < fragments.length; i++) {
                            highlightTitle += fragments[i];
                        }
                    }
                    Map<String, Object> asMap = searchHit.getSourceAsMap();
                    if (StrUtil.isNotEmpty(highlightTitle)) {
                        asMap.put("title", highlightTitle);
                    }
                    list.add(asMap);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return list;
        }
    }
    
    • 测试结果
  • 相关阅读:
    Ant的实现原理
    单例模式
    Ant常用代码段
    [转]大象吃香蕉问题
    i++和++i探秘
    带滚动条的table
    公钥系统/数字签名/数字证书工作原理入门 [转]
    动态创建WPF 控件,并绑定指定Style
    C#如何使用帮助及如何关联到F1键
    Umbraco安装记录
  • 原文地址:https://www.cnblogs.com/everyingo/p/14837272.html
Copyright © 2020-2023  润新知