基于elasticsearch+vue模仿实现京东搜索高亮

https://space.bilibili.com/95256449 原教程地址

创建一个实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Goods {
    private String title;
    private String img;
    private String price;
    private String shop;
}

写爬取数据的方法,此处以京东为例

@Component
public class HtmlParseUtils {

    public ArrayList<Goods> getlist(String keyword) throws IOException {
        //id----J_goodsList
        //ul-----gl-warp clearfix
        //url-----https://search.jd.com/Search?keyword=java
        //attr----attr()是获取或设置某个元素的属性。
        //eq(数字)-----获取当前标签的第(参数+1)个的内容,比如一个页面有多个a标签,getElementsByTag("a").eq(1)就是获取第2个a标签的内容
        //查询的网站url
        String url="https://search.jd.com/Search?keyword="+keyword;
        //解析网站
        Document document = Jsoup.parse(new URL(url), 30000);
        //获得承载信息的div
        Element element = document.getElementById("J_goodsList");
        //获得列表也就是li
        Elements lis = element.getElementsByTag("li");
        //创建一个列表
        ArrayList<Goods> list = new ArrayList<>();
        for (Element li : lis) {
            String img = li.getElementsByTag("img").eq(0).attr("source-data-lazy-img");
            String title = li.getElementsByClass("p-name").eq(0).text();
            String price = li.getElementsByClass("p-price").eq(0).text();
            String shop = li.getElementsByClass("J_im_icon").eq(0).text();
            Goods goods = new Goods();
            goods.setTitle(title);
            goods.setImg(img);
            goods.setPrice(price);
            goods.setShop(shop);
            list.add(goods);
        }
        return list;
    }
}

controller层

@Controller
public class Controllera {
    @Autowired
    private ContenService contenService;

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    //入库
    @GetMapping("/parse/{keyword}")
    @ResponseBody
    public boolean addall(@PathVariable("keyword") String keyword) throws IOException {
        boolean addall = contenService.addall(keyword);
        return addall;
    }

    //查找
    @GetMapping("/get/{keyword}/{page}/{num}")
    @ResponseBody
    public ArrayList<Map<String, Object>> get(@PathVariable("keyword") String keyword,
                                              @PathVariable("page") Integer page,
                                              @PathVariable("num") Integer num) throws IOException {
       return contenService.getall(keyword,page,num);
    }
    //删除
    @GetMapping("/delete")
    @ResponseBody
    public DeleteResponse delte() throws IOException {
        DeleteResponse response = contenService.delete();
        return  response;
    }
}

service层

@Service
public class ContenService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private HtmlParseUtils htmlParseUtils;

    //入库
    public boolean addall(String keyword) throws IOException {
        //先从爬取数据的方法获得信息并放到实体类
        ArrayList<Goods> list = htmlParseUtils.getlist(keyword);
        //创建批量操作的命令
        BulkRequest bulkRequest = new BulkRequest();
        //将数据批量放到索引
        for (int i = 0; i < list.size(); i++) {
            bulkRequest.add(new IndexRequest("jd_index").source(JSON.toJSONString(list.get(i)), XContentType.JSON));
        }
        //执行索引添加操作
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        //bulk.hasFailures()如果为false则成功,所以是!bulk.hasFailures()
        return !bulk.hasFailures();
    }

    public ArrayList<Map<String, Object>>  getall(String keyword, Integer page, Integer num) throws IOException {
        //创建jd_index的索引
        SearchRequest request = new SearchRequest("jd_index");
        //创建搜索命令
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //以title进行精确搜索
        TermQueryBuilder termQueryBuilder = new TermQueryBuilder("title", keyword);
        //执行精确搜索
        sourceBuilder.query(termQueryBuilder);
        if(page<1){
            page=1;
        }
        //设置分页
        sourceBuilder.from(page);
        sourceBuilder.size(num);
        //高亮设置
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:blue'>");
        highlightBuilder.postTags("</span>");
        highlightBuilder.requireFieldMatch(false);//多个高亮显示
        //执行高亮
        sourceBuilder.highlighter(highlightBuilder);
        //套娃执行搜索
        request.source(sourceBuilder);
        //套娃套娃执行索引命令
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        //list存的是map类型的数据
        ArrayList<Map<String,Object>> list=new ArrayList<>();
        //获得数据体
        for (SearchHit fields : response.getHits().getHits()) {
            //获得高亮的字段
            Map<String, HighlightField> highlightFields = fields.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            //获得原生未高亮的字段
            Map<String, Object> sourceAsMap = fields.getSourceAsMap();
            //如果高亮的字段不为空,就把普通字段替换成高亮字段
            if(title != null){
                Text[] texts = title.getFragments();
                String n_title="";
                for (Text text : texts) {
                    n_title+=text;
                }
                sourceAsMap.put("title",n_title);
            }
            list.add(sourceAsMap);
        }
        return list;
    }

    public AcknowledgedResponse delete() throws IOException {
        //创建一个索引删除的命令
        DeleteIndexRequest request = new DeleteIndexRequest("jd_index");
        //执行删除索引的命令
        AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        return response;
    }
}

HTML

<!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>{{result.shop}} </span>
                            </div>
                            <!-- 成交信息 -->
                            <p class="productStatus">
                                <span style="color: chocolate">月成交<em>999笔</em></span>
                                <span>评价 <a>3</a></span>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script th:src="@{/js/axios.min.js}"></script>
<script th:src="@{/js/vue.js}"></script>
<script>
new Vue({
    el : '#app',
    data:{
        keyword :'', //搜索的关键字
        results:[], //搜索的结果
    },
    methods:{
        searchkey(){
            var keyword=this.keyword;
            axios.get('get/'+keyword+"/1/60").then(response=>{
                this.results=response.data;
            })
        }
    }
})
</script>

</body>
</html>

效果图
在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
实现搜索引擎一般需要以下步骤: 1. 数据库建表和数据导入:根据需要建立相应的数据库表,并导入数据。 2. Elasticsearch安装和配置:安装Elasticsearch,配置Elasticsearch集群,并将数据导入到Elasticsearch中。 3. Spring Boot和Vue.js项目搭建:使用Spring Boot和Vue.js框架搭建项目。 4. 搜索功能实现:使用Elasticsearch进行搜索功能的实现。 具体实现步骤如下: 1. 数据库建表和数据导入 根据需求建立相应的数据库表,并将数据导入到数据库中。这里以MySQL为例,建立一个books表: CREATE TABLE `books` ( `id` int NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `author` varchar(255) DEFAULT NULL, `content` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 将数据导入到books表中: INSERT INTO `books` (`id`, `title`, `author`, `content`) VALUES (1, 'Java编程思想', 'Bruce Eckel', 'Java编程思想是一本Java入门书籍。'), (2, 'Spring Boot实战', 'Craig Walls', 'Spring Boot实战是一本介绍Spring Boot框架的书籍。'), (3, 'Vue.js实战', '梁灏', 'Vue.js实战是一本介绍Vue.js框架的书籍。'); 2. Elasticsearch安装和配置 安装Elasticsearch,配置Elasticsearch集群,并将数据导入到Elasticsearch中。这里以Elasticsearch 7.2.0为例,安装步骤如下: (1)下载Elasticsearch 官网下载地址:https://www.elastic.co/downloads/elasticsearch (2)解压并启动Elasticsearch 解压后进入bin目录,执行以下命令启动Elasticsearch: ./elasticsearch (3)安装中文分词器 Elasticsearch默认使用英文分词器,需要安装中文分词器,这里使用IK Analyzer中文分词器。IK Analyzer的GitHub地址为:https://github.com/medcl/elasticsearch-analysis-ik 下载IK Analyzer插件: wget https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.2.0/elasticsearch-analysis-ik-7.2.0.zip 将插件安装到Elasticsearch中: ./elasticsearch-plugin install file:///path/to/elasticsearch-analysis-ik-7.2.0.zip (4)将数据导入到Elasticsearch中 使用Elasticsearch的API将数据库中的数据导入到Elasticsearch中。 3. Spring Boot和Vue.js项目搭建 使用Spring Boot和Vue.js框架搭建项目,这里不再赘述。 4. 搜索功能实现 (1)在Spring Boot中使用Elasticsearch进行搜索 使用Spring Data Elasticsearch实现Elasticsearch的交互,具体步骤如下: 1. 在pom.xml中添加Spring Data Elasticsearch依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> 2. 在application.yml中配置Elasticsearch: spring: data: elasticsearch: cluster-name: elasticsearch cluster-nodes: 127.0.0.1:9300 3. 创建一个Book实体类,并使用@Document注解标注该实体类对应的Elasticsearch索引和类型: @Document(indexName = "books", type = "book") public class Book { @Id private Long id; private String title; private String author; private String content; // getter和setter方法省略 } 4. 创建一个BookRepository接口,继承ElasticsearchRepository接口: public interface BookRepository extends ElasticsearchRepository<Book, Long> { } 5. 在BookService中实现搜索功能: @Service public class BookService { @Autowired private BookRepository bookRepository; public List<Book> search(String keyword) { QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword, "title", "author", "content"); Iterable<Book> iterable = bookRepository.search(queryBuilder); List<Book> books = new ArrayList<>(); iterable.forEach(books::add); return books; } } (2)在Vue.js中调用搜索接口 使用axios库调用Spring Boot的接口,具体步骤如下: 1. 安装axios库: npm install axios --save 2. 在Vue.js中调用搜索接口: <script> import axios from 'axios'; export default { data() { return { keyword: '', books: [] } }, methods: { search() { axios.get('/api/search?keyword=' + this.keyword).then(response => { this.books = response.data; }).catch(error => { console.log(error); }); } } } </script> 以上就是使用Spring Boot和Vue.js实现Elasticsearch搜索引擎的步骤。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值