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.

2.运行后:

 第二步

开始创建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 ";

}


}

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

 

添加完毕了,但是到底是否真的添加进去了呢? 接下来暂时使用 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;
    }

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

其实上面使用的已经是模糊查询了,只是因为我们存入的数据关于masterName只有一条,所以只查询到了一条。

那么接下来我们来增加多一些数据,

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

 

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

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

    @GetMapping("/queryTestDataOne")
    public  String queryTestDataOne(){

        GetQuery query = new GetQuery();
        query.setId("114");

        Blog blog = elasticsearchTemplate.queryForObject(query, Blog.class);
       return blog.toString();
    }

单个查询结果:

那么假如我们不知道主键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;

    }

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

OK,其实 elasticsearch 还提供了很多很多方法给我们使用,类似自定义查询,范围查询,多条件查询等等,该篇教大家入门使用就不展开一一介绍了。等大家学会简单的使用,剩下的就是自己拓展提升,学会使用其他提供的方法之类的。

第三步

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

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

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

 ElasticHD 5.6.0 baidu网盘下载链接:

https://pan.baidu.com/s/1pGPPB9IU6GtXuvaX-B5mdg
提取码: epgp

1.下载安装解压,如:

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

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

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

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

点击搜索即可看到数据:

 

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

发布了181 篇原创文章 · 获赞 289 · 访问量 27万+

猜你喜欢

转载自blog.csdn.net/qq_35387940/article/details/104840473