Springboot 整合 ElasticSearch 入门教学必看

本文涉及的产品
检索分析服务 Elasticsearch 版,2核4GB开发者规格 1个月
简介: Springboot 整合 ElasticSearch 入门教学必看

ElasticSearch 相比搜到这篇文章的人,都已经有过对它的了解,


一种流行的企业级搜索引擎,是一个分布式,高性能、高可用、可伸缩的搜索和分析系统。


那么用我粗俗的言语来说,它就是提供一个存储数据的地方,然后搜索起来很快,特别是联想搜索,也就是模糊查询这种。其他多的在该篇不做介绍。


我所写的springboot整合实践教程,都是从零开始,所以该篇的内容也是一样。

什么是从零开始?


该篇包含内容:


1.基于windows ,下载安装 ElasticSearch(可以理解为一直存取数据的平台);


2.创建Springboot,整合ElasticSearch,使用入门的一些简单操作(插入,查询数据等)。


3.基于windows,下载安装 ElasticHD(一个对于ElasticSearch的可视化web版客户端);


进入正题,


ElasticSearch 我们使用版本为: 5.6.1


ElasticHD 我们使用版本为 :5.6.0


Springboot 我们使用版本为:2.2.0.RELEASE


记住版本非常重要,因为早在半年前我已经踩坑,现在回过头来给大家出个入门教学,踩坑记录:(https://blog.csdn.net/qq_35387940/article/details/91890425


好现在开始进入正题,


第一步



首先是ElasticSearch 5.6.1 版本下载安装,


既然从零教学那就是保证你必须学会,所以不用去网上再搜下载了,


ElasticSearch 5.6.1 baidu网盘下载链接:


https://pan.baidu.com/s/1jvHtoBcH65NW7KMz-XZqPw  

提取码:6jg6


下载完解压,然后进到bin目录,运行elasticsearch.bat 即可,


1.


image.png


2.运行后:


image.png


第二步



开始创建springboot项目,


创建完后,记得把springboot版本改成2.X版本,这里我使用的是2.2.0 RELEASE然后是在pom.xml文件加入需要用到的依赖包,


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </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>


然后是application.yml 文件:


spring:
 data:
  elasticsearch:
    cluster-nodes: 127.0.0.1:9300
server:
  port: 8066


创建一个Blog.class 类,用于测试例子的数据的存取:


注意 这里的@Document(indexName = "testdata", type = "blogs")


indexName  索引名称,其实相当于咱们的数据库名称 ,必须为小写, 不然会报org.elasticsearch.indices.InvalidIndexNameException异常


而type:类型 ,其实相当于咱们的数据库表的名称


import lombok.Data;
import org.springframework.data.elasticsearch.annotations.Document;
/**
 * @Author : JCccc
 * @CreateTime : 2020/3/13
 * @Description :
 **/
@Data
@Document(indexName = "testdata", type = "blogs")
public class Blog {
    private Long id;
    private String masterName;
    private Integer articleNum;
    private Integer commentNum;
    private Integer thumbNum;
    private String description;
}


接着创建一个DataTestController.class,写一些测试的接口:


import com.example.elastucsearchdemo.pojo.Blog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
 * @Author : JCccc
 * @CreateTime : 2020/3/13
 * @Description :
 **/
@RestController
public class DataTestController {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @GetMapping("/addTest")
    public String testElSearch() {
        //该list用于添加需要存入的数据
        List<IndexQuery> indexQueryList = new ArrayList<>();
        //模拟一些数据
        Blog blog = new Blog();
        blog.setId((long) new Random().nextInt(1500));
        blog.setMasterName("JCccc");
        blog.setArticleNum(10);
        blog.setCommentNum(29);
        blog.setThumbNum(100);
        blog.setDescription("分享不仅为了别人,也是为了自己");
        //把这个数据放入indexQueryList
        indexQueryList.add(new IndexQueryBuilder().withObject(blog).build());
        //循环模拟一些数据
        for (int i = 1; i <= 6; i++) {
            Blog blog2 = new Blog();
            blog2.setId((long) new Random().nextInt(1500));
            blog2.setMasterName("Test");
            blog2.setArticleNum(i*60);
            blog2.setCommentNum(i*16);
            blog2.setThumbNum(i*500);
            blog2.setDescription("测试添加"+i);
            indexQueryList.add(new IndexQueryBuilder().withObject(blog2).build());
        }
        elasticsearchTemplate.bulkIndex(indexQueryList);
        return  "add success ";
}
}


运行项目,调用一下这个插入数据的模拟接口:


image.png


image.png


添加完毕了,但是到底是否真的添加进去了呢? 接下来暂时使用 elasticsearchTemplate提供的查询方法来验证下(后面会有相关的ElasticHD可视化客户端下载安装,用来看数据)


写个查询接口:


    @GetMapping("/getTestData")
    public  List<Blog> getTestData(){
        //精确查询
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchPhraseQuery("masterName", "JCccc"))
                .build();
        List<Blog> list = elasticsearchTemplate.queryForList(searchQuery, Blog.class);
        return list;
    }


调用下接口看下,查询正常:


image.png


那么接下来我们来增加多一些数据,进行模糊查询,


    //该list用于添加需要存入的数据
        List<IndexQuery> indexQueryList = new ArrayList<>();
        //循环模拟一些数据
        for (int i = 1; i <= 3; i++) {
            Blog blog2 = new Blog();
            blog2.setId((long) new Random().nextInt(1500));
            blog2.setMasterName("Test"+i*2*3);
            blog2.setArticleNum(i*60);
            blog2.setCommentNum(i*16);
            blog2.setThumbNum(i*500);
            blog2.setDescription("测试添加"+i);
            indexQueryList.add(new IndexQueryBuilder().withObject(blog2).build());
        }
        elasticsearchTemplate.bulkIndex(indexQueryList);


然后在验证下这个模糊搜索:


    @GetMapping("/queryTestData")
    public  List<Blog> getTestData(){
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.wildcardQuery("masterName", ("*" + "Test" + "*").toLowerCase()))
                .build();
        List<Blog> list = elasticsearchTemplate.queryForList(searchQuery, Blog.class);
        return  list;
    }


再调用一下,就可以看到模糊查询出所有包含Test的数据了。


image.png

那么假设已经知道了id,单个数据查询又是如何操作呢?如下,单个根据id查询,


    @GetMapping("/queryTestDataOne")
    public  String queryTestDataOne(){
        GetQuery query = new GetQuery();
        query.setId("114");
        Blog blog = elasticsearchTemplate.queryForObject(query, Blog.class);
       return blog.toString();
    }


单个查询结果:


image.png那么假如我们不知道主键id,我们只知道一些条件,例如想查询 点赞数  thumbNum =1000的 数据,


也就是单条件查询:


这时候我们需要实现自定义查询类ElasticsearchOptionSearchRepository.class,


import com.example.elastucsearchdemo.pojo.Blog;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
/**
 * @Author : JCccc
 * @CreateTime : 2020/3/13
 * @Description :
 **/
@Repository
public interface ElasticsearchOptionSearchRepository extends ElasticsearchRepository<Blog,String> {
}


然后写个接口:


    @Autowired
    private ElasticsearchOptionSearchRepository elasticsearchOptionSearchRepository;
    //根据单条件查询
    @GetMapping("/queryTestDataCondition")
    public  List queryTestDataCondition(){
        List<Blog> list = new ArrayList<>();
        TermQueryBuilder termQuery = new TermQueryBuilder("thumbNum", 1000);
        Iterable<Blog> iterable = elasticsearchOptionSearchRepository.search(termQuery);
        iterable.forEach(e -> list.add(e));
        return list;
    }


运行调用接口,查看情况,都查询出来了:


image.png


其实 elasticsearch  提供了elasticsearchTemplate 和ElasticsearchRepository ,这两样里面都提供了非常多的各种各样的操作数据的方法,想深入的可以点进去看看相关的方法,或者去官方文档去了解下,该篇就不展开了。


第三步



其实到此咱们对于springboot 整合 elasticsearch 已经基本掌握了, 但是光这么插入数据查询数据,还是比较空洞,不免初学者会感觉这跟存缓存差不多,不知道数据到底有没有真正存入。


所以,我们最后一步是,安装使用可视化客户端  ElasticHD 。


依旧,不需要继续在网上找安装包了,我这边提供给大家的windows版本 5.6.0 :


ElasticHD 5.6.0 baidu网盘下载链接:


https://pan.baidu.com/s/1pGPPB9IU6GtXuvaX-B5mdg

提取码: epgp


1.下载安装解压,如:


image.png


2. 不要双击运行记住!
进入到解压的目录下,通过命令执行,如:


image.png


3.运行成功后,会直接弹出ElasticHD的可视化页面 ,如:


image.png


然后咱们可以查看到我们上面的测试插入的数据:


image.png


选择我们刚刚存入数据的index(类似数据库名):


image.png


点击搜索即可看到数据:


image.png


好了,该篇文章篇幅较长,看到这里也得花不少时间,那入门教学就到此吧。


相关实践学习
使用阿里云Elasticsearch体验信息检索加速
通过创建登录阿里云Elasticsearch集群,使用DataWorks将MySQL数据同步至Elasticsearch,体验多条件检索效果,简单展示数据同步和信息检索加速的过程和操作。
ElasticSearch 入门精讲
ElasticSearch是一个开源的、基于Lucene的、分布式、高扩展、高实时的搜索与数据分析引擎。根据DB-Engines的排名显示,Elasticsearch是最受欢迎的企业搜索引擎,其次是Apache Solr(也是基于Lucene)。 ElasticSearch的实现原理主要分为以下几个步骤: 用户将数据提交到Elastic Search 数据库中 通过分词控制器去将对应的语句分词,将其权重和分词结果一并存入数据 当用户搜索数据时候,再根据权重将结果排名、打分 将返回结果呈现给用户 Elasticsearch可以用于搜索各种文档。它提供可扩展的搜索,具有接近实时的搜索,并支持多租户。
相关文章
|
1月前
|
存储 搜索推荐 Java
|
2月前
|
Java
【极问系列】springBoot集成elasticsearch出现Unable to parse response body for Response
【极问系列】springBoot集成elasticsearch出现Unable to parse response body for Response
|
4天前
|
小程序 JavaScript Java
基于SpringBoot+Vue+uniapp微信小程序的教学辅助微信小程序的详细设计和实现
基于SpringBoot+Vue+uniapp微信小程序的教学辅助微信小程序的详细设计和实现
22 0
|
26天前
|
Java 测试技术 Maven
SpringBoot集成Elasticsearch
SpringBoot集成Elasticsearch
22 0
|
1月前
|
消息中间件 Java 关系型数据库
【二十】springboot整合ElasticSearch实战(万字篇)
【二十】springboot整合ElasticSearch实战(万字篇)
208 47
|
2月前
|
存储 关系型数据库 MySQL
ElasticSearch 入门
【2月更文挑战第7天】ElasticSearch 入门 简介 ElasticSearch 的基本概念 ElasticSearch 的查询流程 ElasticSearch 的更新流程
37 2
|
2月前
|
存储 自然语言处理 搜索推荐
ElasticSearch入门篇
ElasticSearch入门篇
|
2月前
|
Java Windows
【极光系列】springBoot集成elasticsearch
【极光系列】springBoot集成elasticsearch
|
2月前
|
Java Docker 容器
springboot整合后台框架(三)整合elasticsearch
springboot整合后台框架(三)整合elasticsearch
34 0
|
15天前
|
数据可视化 索引
elasticsearch head、kibana 安装和使用
elasticsearch head、kibana 安装和使用