SpringBoot框架集成ElasticSearch实现过程示例详解

 更新时间:2021年11月02日 09:54:53   作者:一个大泥球  
这篇文章主要为大家介绍了SpringBoot如何集成ElasticSearch的实现过程示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步

依赖

SpringBoot版本:2.4.2

 <dependencies>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
		  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</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>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2020.0.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2021.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

先了解一下curl方式操作es

在这里插入图片描述

与SpringBoot集成

配置类

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
@Configuration
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo("localhost:9200")
                .build();
        return RestClients.create(clientConfiguration).rest();
    }
}

实体类

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
@Data
@Document(indexName = "product", shards = 3, replicas = 1)
public class Product {
    //必须有 id,这里的 id 是全局唯一的标识,等同于 es 中的"_id"
    @Id
    private Long id;//商品唯一标识
    /**
     * type : 字段数据类型
     * analyzer : 分词器类型
     * index : 是否索引(默认:true)
     * Keyword : 短语,不进行分词
     */
    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String title;//商品名称
    @Field(type = FieldType.Keyword)
    private String category;//分类名称
    @Field(type = FieldType.Double)
    private Double price;//商品价格
    @Field(type = FieldType.Keyword, index = false)
    private String images;//图片地址
}

测试例子

@RestController
@RequestMapping
public class TestESController {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Resource
    ProductMapper productMapper;
    @GetMapping
    public void createIndex() {
        //创建索引,系统初始化会自动创建索引
        System.out.println("创建索引");
    }
    @DeleteMapping
    public void deleteIndex() {
        //创建索引,系统初始化会自动创建索引
        boolean flg = elasticsearchRestTemplate.deleteIndex(Product.class);
        System.out.println("删除索引 = " + flg);
    }
    @PostMapping
    public void save(){
        Product product = new Product();
        product.setId(1L);
        product.setTitle("华为手机");
        product.setCategory("手机");
        product.setPrice(2999.0);
        product.setImages("http://www.atguigu/hw.jpg");
        productMapper.save(product);
    }
    @PutMapping
    public void update(){
        Product product = new Product();
        product.setId(1L);
        product.setTitle("小米 2 手机");
        product.setCategory("手机");
        product.setPrice(9999.0);
        product.setImages("http://www.atguigu/xm.jpg");
        productMapper.save(product);
    }
    @GetMapping("/findById")
    public void findById(){
        Product product = productMapper.findById(1L).get();
        System.out.println(product);
    }
    @GetMapping("/findAll")
    public void findAll(){
        Iterable<Product> products = productMapper.findAll();
        for (Product product : products) {
            System.out.println(product);
        }
    }
    //删除
    @DeleteMapping("/delDocument")
    public void delete(){
        Product product = new Product();
        product.setId(1L);
        productMapper.delete(product);
    }
    //批量新增
    @PostMapping("/addBatch")
    public void saveAll(){
        List<Product> productList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Product product = new Product();
            product.setId(Long.valueOf(i));
            product.setTitle("["+i+"]小米手机");
            product.setCategory("手机");
            product.setPrice(1999.0+i);
            product.setImages("http://www.atguigu/xm.jpg");
            productList.add(product);
        }
        productMapper.saveAll(productList);
    }
    //分页查询
    @GetMapping("/findByPageable")
    public void findByPageable(){
        //设置排序(排序方式,正序还是倒序,排序的 id)
        Sort sort = Sort.by(Sort.Direction.DESC,"id");
        int currentPage=0;//当前页,第一页从 0 开始, 1 表示第二页
        int pageSize = 5;//每页显示多少条
        //设置查询分页
        PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
        //分页查询
        Page<Product> productPage = productMapper.findAll(pageRequest);
        for (Product Product : productPage.getContent()) {
            System.out.println(Product);
        }
    }
}

RestHighLevelClient直接操作

这些操作,就是javaApi,和上图中,通过http方式和es交互式类似的

索引操作

/**
 * 这里时测试,开发时:通过 ESTemplate操作。Spring进行了封装
 */
@Slf4j
public class ESIndexTestCase {
    public static void main(String[] args) throws IOException {
        // 创建客户端
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200)));
        // 创建索引
        // CreateIndexRequest indexRequest = new CreateIndexRequest("book");
        // CreateIndexResponse indexResponse = esClient.indices().create(indexRequest, RequestOptions.DEFAULT);
        // boolean acknowledged = indexResponse.isAcknowledged();
        // log.error("响应{}",acknowledged);
        // 查询索引
        // GetIndexRequest getIndexRequest = new GetIndexRequest("book");
        // GetIndexResponse getIndexResponse = esClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);
        // log.info("getAliases:{}",getIndexResponse.getAliases());
        // log.info("getMappings:{}",getIndexResponse.getMappings());
        // log.info("getSettings:{}",getIndexResponse.getSettings());
        // 删除索引
        AcknowledgedResponse deleteRes = esClient.indices().delete(new DeleteIndexRequest("book"), RequestOptions.DEFAULT);
        boolean delAck = deleteRes.isAcknowledged();
        log.error("delAck:{}",delAck);
        esClient.close();
    }
}

文档操作

@Slf4j
public class ESDocmentTestCase {
    public static void main(String[] args) throws IOException {
        // 创建客户端
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200)));
        // 新增文档
        // IndexRequest indexRequest = new IndexRequest("user");
        // indexRequest.id("1001");       
        // // 准备文档
        // User user = new User();
        // user.setName("张三");
        // user.setAge(22);
        // user.setSex("男");        
        // String userJson = JSONObject.toJSONString(user);
        // indexRequest.source(userJson, XContentType.JSON);
        // IndexResponse indexResponse = esClient.index(indexRequest, RequestOptions.DEFAULT);
        // log.error("getResult:==========>:{}",indexResponse.getResult());
        // 批量新增文档
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.add(new IndexRequest("user").id("2001").source(XContentType.JSON,"name","张三","age","40","sex","男"));
        bulkRequest.add(new IndexRequest("user").id("2002").source(XContentType.JSON,"name","222","age","10","sex","女"));
        bulkRequest.add(new IndexRequest("user").id("2003").source(XContentType.JSON,"name","33333","age","20","sex","男"));
        bulkRequest.add(new IndexRequest("user").id("2004").source(XContentType.JSON,"name","111","age","30","sex","男"));
        bulkRequest.add(new IndexRequest("user").id("2005").source(XContentType.JSON,"name","2222","age","31","sex","女"));
        BulkResponse bulkResponse = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        log.error("getResult:==========>:{}",bulkResponse.getTook());
        // 更新文档(全量更新,局部更新)

        // UpdateRequest updateRequest = new UpdateRequest("user", "1001");
        // updateRequest.doc("sex","dddddd");
        // UpdateResponse updateResponse = esClient.update(updateRequest, RequestOptions.DEFAULT);
        // log.error("getResult:==========>:{}",updateResponse.getResult());

        // 根据_id查询文档
        // GetRequest getRequest = new GetRequest("user", "1001");
        // GetResponse getResponse = esClient.get(getRequest, RequestOptions.DEFAULT);
        // log.error("getResult:==========>:{}",getResponse.getSource());

        // 根据_id 删除数据
        // DeleteRequest deleteRequest = new DeleteRequest("user", "1001");
        // DeleteResponse deleteResponse = esClient.delete(deleteRequest, RequestOptions.DEFAULT);
        // log.error("getResult:==========>:{}",deleteResponse.getResult());

        // 批量删除(和批量新增类似)
        esClient.close();
    }
}

检索操作

@Slf4j
public class EsSearchTest {
    public static void main(String[] args) throws IOException {
        // 创建客户端
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200)));
        // 查询所有
        // SearchRequest searchRequest = new SearchRequest("user");
        // SearchSourceBuilder queryBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        // queryBuilder.from(0);
        // queryBuilder.size(4);
        // queryaBuilder.sort("age", SortOrder.DESC);
        // SearchRequest sourceRequest = searchRequest.source(queryBuilder);
        // SearchResponse searchResponse = esClient.search(sourceRequest, RequestOptions.DEFAULT);
        // log.error("getHits:======>{}", searchResponse.getHits().getTotalHits());
        // searchResponse.getHits().forEach(hit -> System.out.println(hit.getSourceAsString()));
        // 2-组合查询
        // SearchRequest searchRequest = new SearchRequest("user");
        // BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // // 这里就是组合条件。和mysql where 组合类似
        // boolQueryBuilder.should(QueryBuilders.matchQuery("age","30"));
        // boolQueryBuilder.should(QueryBuilders.matchQuery("age","40"));
        // SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(boolQueryBuilder);
        // searchRequest.source(sourceBuilder);
        // SearchResponse searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
        // searchResponse.getHits().forEach(hit -> System.err.println(hit.getSourceAsString()));
        // 3-范围查询
        // SearchRequest searchRequest = new SearchRequest("user");
        // SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
        // rangeQuery.gte("30");
        // sourceBuilder.query(rangeQuery);
        // searchRequest.source(sourceBuilder);
        // SearchResponse searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
        // searchResponse.getHits().forEach(hit -> System.out.println(hit.getSourceAsString()));
        //4-模糊查询+高亮
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        FuzzyQueryBuilder fuzzyQuery = QueryBuilders.fuzzyQuery("name", "张三");
        sourceBuilder.query(fuzzyQuery);
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("name");
        sourceBuilder.highlighter(highlightBuilder);
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
        searchResponse.getHits().forEach(System.out::println);
        // 5-聚合查询
        esClient.close();
    }
}

内容来自B站

https://www.bilibili.com/video/BV1hh411D7sb?p=62

以上就是SpringBoot集成ElasticSearch实现过程示例详解的详细内容,更多关于SpringBoot框架集成ES的资料请关注脚本之家其它相关文章!

相关文章

  • 老生常谈Java中instanceof关键字的理解

    老生常谈Java中instanceof关键字的理解

    java 中的instanceof 运算符是用来在运行时指出对象是否是特定类的一个实例。这篇文章主要介绍了老生常谈Java中instanceof关键字的理解,需要的朋友可以参考下
    2018-10-10
  • 详解Java去除json数据中的null空值问题

    详解Java去除json数据中的null空值问题

    这篇文章主要介绍了详解Java去除json数据中的null空值问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-08-08
  • 值得收藏的2017年Java开发岗位面试题

    值得收藏的2017年Java开发岗位面试题

    这篇文章主要为大家推荐一份值得收藏的2017年Java开发岗位面试题,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-08-08
  • 解读spark添加二方包导致依赖冲突排查问题

    解读spark添加二方包导致依赖冲突排查问题

    这篇文章主要介绍了spark添加二方包导致依赖冲突排查问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-06-06
  • Java中使用DOM4J生成xml文件并解析xml文件的操作

    Java中使用DOM4J生成xml文件并解析xml文件的操作

    这篇文章主要介绍了Java中使用DOM4J来生成xml文件和解析xml文件的操作,今天通过代码给大家展示了解析xml文件和生成xml文件的方法,需要的朋友可以参考下
    2021-09-09
  • SpringBoot通过注解注入Bean的几种方式解析

    SpringBoot通过注解注入Bean的几种方式解析

    这篇文章主要为大家介绍了SpringBoot注入Bean的几种方式示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加薪
    2022-03-03
  • 在mybatis中去除多余的前缀或者后缀操作

    在mybatis中去除多余的前缀或者后缀操作

    这篇文章主要介绍了在mybatis中去除多余的前缀或者后缀操作。具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-11-11
  • SpringBoot3集成SLF4J+logback进行日志记录的实现

    SpringBoot3集成SLF4J+logback进行日志记录的实现

    本文主要介绍了SpringBoot3集成SLF4J+logback进行日志记录的实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • MyBatis中useGenerateKeys的使用解析

    MyBatis中useGenerateKeys的使用解析

    这篇文章主要介绍了MyBatis中useGenerateKeys的使用,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • SpringCloud高可用配置中心Config详解

    SpringCloud高可用配置中心Config详解

    Spring Cloud Config 是一个解决分布式系统的配置管理方案,它包含了 server 和 client 两个部分,这篇文章主要介绍了SpringCloud之配置中心Config(高可用),需要的朋友可以参考下
    2022-04-04

最新评论