代码编织梦想

上一章:《第三章:ElasticSearch相关概念》



上述部分为理论部分,本章跟着我一起来看一下具体开发中es是如何使用的

本章的完整代码在文末可以自行查看下载

4.1 导入elasticsearch依赖

在pom.xml里加入如下依赖:

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

我的SpringBoot版本:2.6.2
引入之后记得要看一下你的依赖版本是否和es的版本是否适配,如果不一致,会连接失败
在这里插入图片描述

启动es,在浏览器输入http://localhost:9200/查看es版本
在这里插入图片描述

很明显,我们的版本是不兼容的,我找了半天spring-boot-starter-data-elasticsearch依赖包也没找到适配es 8.6.1的依赖,为了不影响进度,我先退而求其次,先使用7.15.2这个版本的es

安装包:https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.15.2-windows-x86_64.zip

安装过程和我们第二章的过程一样,详情可参考:《第二章:ElasticSearch安装》

安装之后,我们可以看到我们的版本号已经变为7.15.2啦
在这里插入图片描述

4.2 创建高级客户端

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchClientConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9200, "http")));
        return client;
    }
}

如果你的es是部署在服务器上,那么127.0.0.1则需要改成你服务器的ip地址

4.3 基本用法

1.创建、判断存在、删除索引

  • 创建索引
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    /**
     * 创建索引
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/index/createIndex")
    public Object createIndex() throws IOException {
        //1.创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("ninesunindex");
        //2.客户端执行请求IndicesClient,执行create方法创建索引,请求后获得响应
        CreateIndexResponse response =
                restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        return response;
    }

在这里插入图片描述

可以看到索引已经创建成功

PS:如果不知道索引以及我们后面提到的名次概念,可以花几分钟读一下:《第三章:ElasticSearch相关概念》

  • 查询索引
    /**
     * 查询索引
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/index/searchIndex")
    public Object searchIndex() throws IOException {
        //1.查询索引请求
        GetIndexRequest request = new GetIndexRequest("ninesunindex");
        //2.执行exists方法判断是否存在
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        return exists;
    }
  • 删除索引
    /**
     * 删除索引
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/index/delIndex")
    public Object delIndex() throws IOException {
        //1.删除索引请求
        DeleteIndexRequest request = new DeleteIndexRequest("ninesunindex");
        //执行delete方法删除指定索引
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        return delete.isAcknowledged();
    }

2.对文档的CRUD

创建文档:

注意:如果添加时不指定文档ID,他就会随机生成一个ID,ID唯一。

创建文档时若该ID已存在,发送创建文档请求后会更新文档中的数据

  • 新增文档
    /**
     * 新增文档
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/document/add")
    public Object add() throws IOException {
        //1.创建对象
        User user = new User("Go", 21, new String[]{"内卷", "吃饭"});
        //2.创建请求
        IndexRequest request = new IndexRequest("ninesunindex");
        //3.设置规则 PUT /ljx666/_doc/1
        //设置文档id=6,设置超时=1s等,不设置会使用默认的
        //同时支持链式编程如 request.id("6").timeout("1s");
        request.id("6");
        request.timeout("1s");

        //4.将数据放入请求,要将对象转化为json格式
        //XContentType.JSON,告诉它传的数据是JSON类型
        request.source(JSONValue.toJSONString(user), XContentType.JSON);

        //5.客户端发送请求,获取响应结果
        IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(indexResponse.toString());
        System.out.println(indexResponse.status());
        return indexResponse;
    }
  • 获取文档中的数据
    /**
     * 获取文档中的数据
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/document/get")
    public Object get() throws IOException {
        //1.创建请求,指定索引、文档id
        GetRequest request = new GetRequest("ninesunindex", "6");
        GetResponse getResponse = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        System.out.println(getResponse);//获取响应结果
        //getResponse.getSource() 返回的是Map集合
        System.out.println(getResponse.getSourceAsString());//获取响应结果source中内容,转化为字符串
        return getResponse;
    }
  • 更新文档数据

注意:需要将User对象中的属性全部指定值,不然会被设置为空,如User只设置了名称,那么只有名称会被修改成功,其他会被修改为null。

    /**
     * 更新文档数据
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/document/update")
    public Object update() throws IOException {
        //1.创建请求,指定索引、文档id
        UpdateRequest request = new UpdateRequest("ninesunindex", "6");

        User user = new User("GoGo", 21, new String[]{"内卷", "吃饭"});
        //将创建的对象放入文档中
        request.doc(JSONValue.toJSONString(user), XContentType.JSON);
        UpdateResponse updateResponse = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        System.out.println(updateResponse.status());//更新成功返回OK
        return updateResponse;
    }
  • 删除文档数据
    /**
     * 删除文档数据
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/document/delete")
    public Object delete() throws IOException {
        //1.创建删除文档请求
        DeleteRequest request = new DeleteRequest("ninesunindex", "6");
        DeleteResponse deleteResponse = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(deleteResponse.status());//更新成功返回OK
        return deleteResponse;
    }

  

3.批量新增文档数据

  • 批量新增文档数据
    /**
     * 批量新增文档数据
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/document/addBatch")
    public Object addBatch() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        //设置超时
        bulkRequest.timeout("10s");

        List<User> list = new ArrayList<>();
        list.add(new User("Java", 25, new String[]{"内卷"}));
        list.add(new User("Go", 18, new String[]{"内卷"}));
        list.add(new User("C", 30, new String[]{"内卷"}));
        list.add(new User("C++", 26, new String[]{"内卷"}));
        list.add(new User("Python", 20, new String[]{"内卷"}));

        int id = 1;
        //批量处理请求
        for (User u : list) {
            //不设置id会生成随机id
            bulkRequest.add(new IndexRequest("ninesunindex")
                    .id("" + (id++))
                    .source(JSONValue.toJSONString(u), XContentType.JSON));
        }

        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.hasFailures());//是否执行失败,false为执行成功
        return bulkResponse;
    }

4.查询所有、模糊查询、分页查询、排序、高亮显示

    @GetMapping("test")
    public Object test() throws IOException {
        SearchRequest searchRequest = new SearchRequest("ninesunindex");//里面可以放多个索引
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//构造搜索条件
        //此处可以使用QueryBuilders工具类中的方法
        //1.查询所有
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        //2.查询name中含有Java的
        sourceBuilder.query(QueryBuilders.multiMatchQuery("java", "userName"));
        //3.分页查询
        sourceBuilder.from(0).size(5);
        //4.按照score正序排列
        sourceBuilder.sort(SortBuilders.scoreSort().order(SortOrder.ASC));
        //5.按照id倒序排列(score会失效返回NaN)
        sourceBuilder.sort(SortBuilders.fieldSort("_id").order(SortOrder.DESC));
        //6.给指定字段加上指定高亮样式
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("userName").preTags("<span style='color:red;'>").postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //获取总条数
        System.out.println(searchResponse.getHits().getTotalHits().value);
        //输出结果数据(如果不设置返回条数,大于10条默认只返回10条)
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println("分数:" + hit.getScore());
            Map<String, Object> source = hit.getSourceAsMap();
            System.out.println("index->" + hit.getIndex());
            System.out.println("id->" + hit.getId());
            for (Map.Entry<String, Object> s : source.entrySet()) {
                System.out.println(s.getKey() + "--" + s.getValue());
            }
        }
        return searchResponse;
    }

4.4 总结

1.大致流程

创建对应的请求 --> 设置请求(添加规则,添加数据等) --> 执行对应的方法(传入请求,默认请求选项)–> 接收响应结果(执行方法返回值)–> 输出响应结果中需要的数据(source,status等)

2.注意事项

如果不指定id,会自动生成一个随机id

正常情况下,不应该这样使用new IndexRequest(“indexName”),如果索引发生改变了,那么代码都需要修改,可以定义一个枚举类或者一个专门存放常量的类,将变量用final static等进行修饰,并指定索引值。其他地方引用该常量即可,需要修改也只需修改该类即可。

elasticsearch相关的东西,版本都必须一致,不然会报错

elasticsearch很消耗内存,建议在内存较大的服务器上运行elasticsearch,否则会因为内存不足导致elasticsearch自动killed


git地址:https://gitee.com/ninesuntec/es-better.git

下一章:《第五章:ElasticSearchRepository和ElasticsearchRestTemplate的使用

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zhiyikeji/article/details/128902860

springboot 整合 elasticsearch 之 elasticsearchrepository 的 crud、分页接口_aa1215018028的博客-爱代码爱编程_elasticsearchrepository分页

一、前言 这里写图片描述 前面使用了 SpringBoot 整合了 Solr: [增删改查] SpringBoot 整合 Solr 实现 CRUD、分页接口、高亮显示 眼下有一个比 Solr 还火热的 ElasticSearch,主要是用于大数据、分布式系统中,顺便使用 SpringBoot 来整合     Elasticsearch是一个基于Luc

ElasticSearch-使用SpringDataElasticSearch完成增删改查,分页查询,特殊条件查询,高亮查询案例-爱代码爱编程

文章目录 1. 导入pom.xml坐标依赖2. SpringBoot 环境搭建2.0 创建启动类2.1 创建application.yml配置文件2.2 创建实体类 ArticleDocument2.3 创建ArticleDao接口2.4 创建ArticleService 接口2.5 创建 ArticleServiceImpl 实现类2.6 创建测

springboot+elasticsearch 实现模糊查询,批量crud,排序,分页,高亮_公众号:方志朋的博客-爱代码爱编程

点击关注公众号,实用技术文章及时了解 导入elasticsearch依赖创建高级客户端基本用法 创建、判断存在、删除索引对文档的CRUD批量CRUD数据查询所有、模糊查询、分页查询、排序、高亮显示总结 大致流程注意事项 一、导入elasticsearch依赖 在pom.xml里加入如下依赖 <dependency>   

springboot + elasticsearch 实现模糊查询,批量crud,排序,分页,高亮!-爱代码爱编程

一、引入依赖 当前Elasticsearch服务端的版本为8.5.1,此处Spring Data Elasticsearch的版本为2.6.1 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spri

springboot+elasticsearch 实现模糊查询,批量crud,排序,分页,高亮!-爱代码爱编程

         一、导入elasticsearch依赖 在pom.xml里加入如下依赖 <dependency>       <groupId>org.springframework.boot</groupId>       <artifactId>spring-boot-starter-data-e

springboot+elasticsearch 实现模糊查询,批量crud,排序,分页,高亮-爱代码爱编程

一、导入elasticsearch依赖 在pom.xml里加入如下依赖 <dependency>       <groupId>org.springframework.boot</groupId>       <artifactId>spring-boot-starter-data-elasticsear

《linux运维实战:centos7.6基于ansible一键离线部署elasticsearch7.6.2容器版分布式集群》-爱代码爱编程

一、部署背景 由于业务系统的特殊性,我们需要针对不同的客户环境部署elasticsearch集群,由于大都数用户都是专网环境,无法使用外网,为了更便捷,高效的部署,针对业务系统的特性,我这边编写了基于ansible自动化

java基础巩固-宇宙第一aiywm:为了维持生计,大数据之elasticsearch【elasticsearch的概念、关于文档、索引的命令】~整起-爱代码爱编程

ElasticSearch 一、ElasticSearch基本概念1.ElasticSearch是什么?从哪来、来干啥?2.ElasticSearch与Solr的对比与选型:3.ES核心概念及相关操作4.ELK:拆箱

第一章:elasticsearch简介-爱代码爱编程

Elaticsearch,简称为es, es是一个开源的高扩展的分布式全文检索引擎,它可以近乎实时的存储、检索数据; 本身扩展性很好,可以扩展到上百台服务器,处理PB级别的数据。 es也使用Java开发并使用Lucene

使用es模式开发一个cli-把当前脚手架和所涉及到的通用基础功能封装到一个cli中来实现快速创建小程序-爱代码爱编程

我们在前端创建一个新的小程序项目时,通常通过ctrl+c和ctrl+v拷贝原有项目结构。其实每个项目的脚手架编译可能还有大大小小的区别,我们想在组内统一是比较困难的,那如果改变这种情况呢?我们可以将当前脚手架以及所涉及到的通用的基础功能封装到一个cli中,大家统一在这个基础上去进行项目构建。也方便以后统

通过zipkin服务中的api查询不到elasticsearch中的数据分析-爱代码爱编程

场景: zipkin链路日志在elasticsearch中正常生成链路数据,当数据通过es查询traceId数据是存在的,但是调用zipkin的api却查询不到当天数据之前的数据。  当天的数据再es中是存在的    当天之前的数据再es中也是存在的   以上说明zipkin在es中数据是正常写入的是正常。 问题一:

springboot 官方文档示例:(71)分别使用repository和template把数据保存到elastisearch和数据查询-爱代码爱编程

一、添加依赖 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"

springboot集成elasticsearch,实现模糊查询,批量crud,排序,分页,高亮_springboot jpa实现elastic模糊查询-爱代码爱编程

文章目录 一、导入elasticsearch依赖二、创建高级客户端三、基本用法1.创建、判断存在、删除索引2.对文档的CRUD3.批量CRUD数据4.查询所有、模糊查询、分页查询、排序、高亮显示 四、总结

重学elasticsearch第7章 : springboot整合springdataelasticsearch_spring data elasticsearch7-爱代码爱编程

文章目录 Spring Data ElasticSearch介绍1.1、SpringData介绍1.2、Spring Data Elasticsearch介绍 引入依赖、yml配置、实体类继承Elasti

重学elasticsearch第8章 : springboot整合jest客户端-爱代码爱编程

文章目录 JestClient介绍引入依赖ES的配置(1)、application.yml 配置文件(2)、java 连接配置类 JestClient操作ElasticSearch客户端初始化索引创建Ma

【谷粒商城高级篇】缓存与分布式锁-爱代码爱编程

谷粒商城笔记合集 分布式基础篇分布式高级篇高可用集群篇===简介&环境搭建======Elasticsearch===项目简介与分布式概念(第一、二章)Elasticsearch:全文检索(第一章)基

2023-爱代码爱编程

对于jdk的理解: http://localhost:9201/ { "name":"node-1001 节点名字", "cluster_name":"my-application 集群名称",

elasticsearch相关概念-爱代码爱编程

上一章:《ElasticSearch安装》 文章目录 3.1 概述3.2 核心概念index索引type类型Filed字段映射mappingdocument文档集群cluster①发现机制②节点的角色③脑

【谷粒商城高级篇】商城业务:商品检索-爱代码爱编程

谷粒商城笔记合集 分布式基础篇分布式高级篇高可用集群篇===简介&环境搭建======Elasticsearch===项目简介与分布式概念(第一、二章)Elasticsearch:全文检索(第一章)基