SpringBoot整合ElasticSearch之Java High Level REST Client

这篇具有很好参考价值的文章主要介绍了SpringBoot整合ElasticSearch之Java High Level REST Client。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1 搭建SpringBoot工程

2 引入ElasticSearch相关坐标。

<properties>
    		<!--一定重新定义版本   版本号一定要和您所安装的ES版本号一致-->
        <elasticsearch.version>7.4.0</elasticsearch.version>
</properties>
<dependencies>
    <!--引入es的坐标-->
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.4.0</version>
    </dependency>
    ................

3 编写核心配置类

编写核心配置文件:

这里可以不写在配置,可以直接写在代码中,只是一般都是写在配置文件中

#这个是我们自写的,如果看有es提示,不要用
elasticsearch:
  host: 192.168.126.20   
  port: 9200

编写核心配置类

@Configuration
@ConfigurationProperties(prefix="elasticsearch")
public class ElasticSearchConfig {

    private String host;
    private int port;

    @Bean
    public RestHighLevelClient client(){
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost(host,port,"http")
        ));
    }  
    
    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}

4 测试客户端对象

记得把maven的单元测试关了

springboot集成resthighlevelclient,ES,springboot,java,elasticsearch,spring boot

注意:使用@Autowired注入RestHighLevelClient 如果报红线,则是因为配置类所在的包和测试类所在的包,包名不一致造成的

@SpringBootTest
class SpringElasticsearchApplicationTests {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Test
    void contextLoads() {
        System.out.println(restHighLevelClient);
    }
}

(二)操作ElasticSearch

操作索引要索引的对象来进行操作

//获取索引对象     这个对象提供操作索引的方法
IndicesClient indices = client.indices();
//添加索引对象    RequestOptions.DEFAULT默认的动作
indices.create(new CreateIndexRequest("offcn_index3"),RequestOptions.DEFAULT);
//查询索引对象
indices.get(new GetIndexRequest("offcn_index3"),RequestOptions.DEFAULT);
//删除索引对象
indices.delete(new DeleteIndexRequest("offcn_index3"),RequestOptions.DEFAULT);

1 添加索引

/**
 * 添加索引:
 * @throws Exception
 */
@Test
   public void addindex() throws IOException {
       // 获取索引对象
       IndicesClient indices = client.indices();
       //create()  CreateIndexRequest("索引名称")    RequestOptions.DEFAULT默的行为
       CreateIndexResponse indexResponse = indices.create(new CreateIndexRequest("student123"), RequestOptions.DEFAULT);
       System.out.println(indexResponse.isAcknowledged());
   }

2 添加索引,并添加映射

/**
  * 创建索引并且添加映射
  * @throws IOException
  */
@Test
public void addIndexAndMapping() throws IOException {
    //1.使用client获取操作索引的对象
    IndicesClient indicesClient = restHighLevelClient.indices();
    //2.具体操作,获取返回值
    CreateIndexRequest createRequest = new CreateIndexRequest("offcn");
    //2.1 设置mappings
    String mapping = "{\n" +
        "      \"properties\" : {\n" +
        "        \"address\" : {\n" +
        "          \"type\" : \"text\",\n" +
        "          \"analyzer\" : \"ik_max_word\"\n" +
        "        },\n" +
        "        \"age\" : {\n" +
        "          \"type\" : \"long\"\n" +
        "        },\n" +
        "        \"name\" : {\n" +
        "          \"type\" : \"keyword\"\n" +
        "        }\n" +
        "      }\n" +
        "    }";
    createRequest.mapping(mapping, XContentType.JSON);
    //2.2执行创建,返回对象
    CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT);
    //3.根据返回值判断结果
    System.out.println(response.isAcknowledged());
}

3 查询、删除、判断索引

3.1 查询索引
/**
  * 查询索引
  */
@Test
public void queryIndex() throws IOException {
    //1:使用client获取操作索引的对象
    IndicesClient indices = restHighLevelClient.indices();
    //2:获得对象,执行具体的操作
    //2.1 创建获取索引的请求对象,设置索引名称
    GetIndexRequest getReqeust = new GetIndexRequest("offcn");
    //2.2 执行查询,获得返回值
    GetIndexResponse response = indices.get(getReqeust, RequestOptions.DEFAULT);
    //3:获取结果,遍历
    Map<String, MappingMetaData> mappings = response.getMappings();
    for (String key : mappings.keySet()) {
        System.out.println(key + ":" + mappings.get(key).getSourceAsMap());
    }
}  
3.2 删除索引
/**
  * 删除索引
  */
@Test
public void deleteIndex() throws IOException {
    IndicesClient indices = restHighLevelClient.indices();
    DeleteIndexRequest deleteRequest = new DeleteIndexRequest("offcn");
    AcknowledgedResponse response = indices.delete(deleteRequest, RequestOptions.DEFAULT);
    System.out.println(response.isAcknowledged());
}
3.3 索引是否存在
/**
  * 判断索引是否存在
  */
@Test
    public void getIndex() throws IOException {
        IndicesClient indices = client.indices();
        GetIndexRequest student0517 = new GetIndexRequest("student0517");
        boolean exists = indices.exists(student0517, RequestOptions.DEFAULT);
        if(exists){
            GetIndexResponse indexResponse = indices.get(student0517, RequestOptions.DEFAULT);
            Map<String, MappingMetaData> mappings = indexResponse.getMappings();
            System.out.println(mappings);
        }else{
            System.out.println("索引不存在");
        }
    }

4 操作文档

4.1 添加文档

添加文档,使用map作为数据

/**
  * 添加文档,使用map作为数据
  */
@Test
public void addDoc() throws IOException {
    //数据对象,map   key要与映射属性对应
    Map data = new HashMap();
    data.put("address", "北京昌平");
    data.put("name", "马同志");
    data.put("age", 20);

    //1:获取操作文档的对象
    IndexRequest request = new IndexRequest("offcn").id("1").source(data);
    //2:添加数据,获取结果
    IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    //3:打印响应结果
    System.out.println(response.getResult());
}

添加文档,使用对象作为数据

添加依赖

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>

创建实体类,属性名与映射字段名对应

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private String brand;
    private Integer price;
    private String title;
}


{
  "sutdent78" : {
    "mappings" : {
      "properties" : {
        "brand" : {
          "type" : "keyword"
        },
        "price" : {
          "type" : "integer"
        },
        "title" : {
          "type" : "text",
          "analyzer" : "ik_max_word"
        }
      }
    }
  }
}
/**
  * 添加文档,使用对象作为数据
  */
@Test
public void addDoc2() throws IOException {
    //数据对象,javaObject
    Student student=new Student("kaka",22,"南沙中公教育");

    //将对象转为json
    String data = JSON.toJSONString(p);
    //1:获取操作文档的对象
    IndexRequest request = new IndexRequest("offcn").id(p.getId()).source(data, XContentType.JSON);
    //2:添加数据,获取结果
    IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    //3:打印响应结果
    System.out.println(response.getId());
}
4.2 修改文档:添加文档时,如果id存在则修改,id不存在则添加
/**
  * 修改文档:添加文档时,如果id存在则修改,id不存在则添加
  */
@Test
public void updateDoc() throws IOException {
    //数据对象,map
    Map data = new HashMap();
    data.put("address", "北京昌平");
    data.put("name", "朱同志");
    data.put("age", 20);

    //1:获取操作文档的对象
    IndexRequest request = new IndexRequest("offcn").id("1").source(data);
    //2:添加数据,获取结果
    IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    //3:打印响应结果
    System.out.println(response.getId());
}
4.3 根据id查询文档
    @Test
    public void getDoc() throws IOException {
        GetRequest getRequest = new GetRequest("sutdent78").id("1002");
        GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        //集合方式
        Map<String, Object> source = documentFields.getSource();
        for (String key : source.keySet()) {
            System.out.println(source.get(key));
        }
        //字符串  -----JSON
        String sourceAsString = documentFields.getSourceAsString();
        System.out.println(sourceAsString);
        //把JSON转换为 stuent
        //JSON字符串-->JSON对象
        JSONObject jsonObject = JSONObject.parseObject(sourceAsString);
        //JSON对象-->Java对象
        Student student = JSONObject.toJavaObject(jsonObject, Student.class);
        System.out.println(student);

    }
4.4 根据id删除文档
/**
  * 根据id删除文档
  */
@Test
public void delDoc() throws IOException {
    DeleteRequest deleteRequest = new DeleteRequest("offcn", "1");
    DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
    System.out.println(response.getId());
}

总结:

//添加、修改   第一个:索引名称   第二个是文档id     第三个是文档内容
restHighLevelClient
    .index( new IndexRequest("offcn_index2").id("as1122").source(data),RequestOptions.DEFAULT)
//查询    第一个参数是索引名称   第二个是文档id
restHighLevelClient.get( new GetRequest("offcn_index2","as1122"),RequestOptions.DEFAULT)
//删除    第一个参数是索引名称   第二个是文档id
restHighLevelClient.delete( new DeleteRequest("offcn_index2","as1122"),RequestOptions.DEFAULT)

(三)ElasticSearch的文档批量操作

1 bulk文档 批量操作脚本实现

需求:同时完成【删除,更新,添加】操作 这里的JSON格式不能格式化

POST _bulk
{"delete":{"_index":"person1","_id":"4"}}
{"create":{"_index":"person1","_id":"5"}}
{"name":"八号","age":18,"address":"北京"}
{"update":{"_index":"person1","_id":"2"}}
{"doc":{"name":"2号"}}

查询运行结果~ 

2 bulk批量操作JavaAPI 实现

/**
     *  Bulk 批量操作
     */
    @Test
    public void test2() throws IOException {

        //创建bulkrequest对象,整合所有操作
        BulkRequest bulkRequest =new BulkRequest();

           /*
        # 1. 删除5号记录
        # 2. 添加6号记录
        # 3. 修改3号记录 名称为 “三号”
         */
        //添加对应操作
        //1. 删除5号记录
        DeleteRequest deleteRequest=new DeleteRequest("person1","5");
        bulkRequest.add(deleteRequest);

        //2. 添加6号记录
        Map<String, Object> map=new HashMap<>();
        map.put("name","六号");
        IndexRequest indexRequest=new IndexRequest("person1").id("6").source(map);
        bulkRequest.add(indexRequest);
        //3. 修改3号记录 名称为 “三号”
        Map<String, Object> mapUpdate=new HashMap<>();
        mapUpdate.put("name","三号");
        UpdateRequest updateRequest=new UpdateRequest("person1","3").doc(mapUpdate);

        bulkRequest.add(updateRequest);
        //执行批量操作

        BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(response.status());
    }

官方文档:
https://www.elastic.co/guide/en/elasticsearch/client/index.html

Java REST Client 》Java High Level REST Client文章来源地址https://www.toymoban.com/news/detail-745528.html

到了这里,关于SpringBoot整合ElasticSearch之Java High Level REST Client的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • elasaticsearch新版java客户端ElasticsearchClient详细教程,支持响应式编程,Lambda表达式,兼容旧版High Level Rest Client

    elasaticsearch新版java客户端详细教程,支持响应式编程,Lambda表达式。兼容旧版High Level Rest Client。网上相关教程少,我在这里出一个。elasaticsearch相关安装这里不介绍了 有几种方式,这里介绍两种,如果不考虑之前旧版High Level Rest Client的客户端采用第一种就行 阻塞和异步客户

    2023年04月15日
    浏览(27)
  • Java SpringBoot整合elasticsearch 7.17相关问题记录

    话不多说直接上代码,首先关注点Springboot相关ES相关的版本对应 找到对应的版本号,我这里对应7.17.1 对应的springboot版本 2.3.* 即可 上图为Springboot相关依赖 ES 创建索引以及映射相关(首先映射分词要保持环境中Es下的分词器安装正确) //创建索引 对应的增删改查 //增加 文档

    2024年02月11日
    浏览(32)
  • java-springboot整合ElasticSearch8.2复杂查询

    近期有大数据项目需要用到es,而又是比较新的es版本,网上也很少有8.x的java整合教程,所有写下来供各位参考。 首先 1.导包: 2.客户端连接代码EsUtilConfigClint: 一开始按照其他博主的方法,长时间连接不操作查询再次调用查询时会报错timeout,所以要设置RequestConfigCallback 3

    2024年02月11日
    浏览(42)
  • SpringBoot整合最新Elasticsearch Java API Client 7.16教程

        最新在学习SpringBoot整合es的一些知识,浏览了网上的一些资料,发现全都是es很久之前的版本了,其中比较流行的是Java REST Client的High Level Rest Client版本,但是官方文档的说明中,已经申明该版本即将废弃,不再进行维护了。可见:官方文档     目前官方推荐的版本是

    2023年04月24日
    浏览(29)
  • java SpringBoot2.7整合Elasticsearch(ES)7 进行文档增删查改

    首先 我们在 ES中加一个 books 索引 且带有IK分词器的索引 首先 pom.xml导入依赖 application配置文件中编写如下配置 spring.elasticsearch.hosts: 172.16.5.10:9200 我这里是用的yml格式的 告诉它指向 我们本地的 9200服务 然后 我们在启动类同目录下 创建一个叫 domain的包 放属性类 然后在这个包

    2024年02月19日
    浏览(36)
  • 【Elasticsearch学习笔记五】es常用的JAVA API、es整合SpringBoot项目中使用、利用JAVA代码操作es、RestHighLevelClient客户端对象

    目录 一、Maven项目集成Easticsearch 1)客户端对象 2)索引操作 3)文档操作 4)高级查询 二、springboot项目集成Spring Data操作Elasticsearch 1)pom文件 2)yaml 3)数据实体类 4)配置类 5)Dao数据访问对象 6)索引操作 7)文档操作 8)文档搜索 三、springboot项目集成bboss操作elasticsearch

    2023年04月09日
    浏览(38)
  • Elasticsearch Java REST Client 批量操作(Bulk API)

    上一篇:Elasticsearch Java REST Client Term Vectors API 下一篇:Elasticsearch Java REST Client Search APIs 查询 BulkRequest可用于使用单个请求执行多个索引、更新和/或删除操作。 它需要至少一个操作添加到 Bulk 请求中: multiGetAPI 在单个 http 请求中并行执行多个请求get 。 MultiGetRequest,添加 `M

    2024年02月11日
    浏览(40)
  • Elasticsearch基础,SpringBoot整合Elasticsearch

    Elasticsearch,简称为es,es是一个开源的高扩展的分布式全文检索引擎,它可以近乎实时的存储、检索数据;本身扩展性很好,可以扩展到上百台服务器,处理PB级别(大数据时代)的数据。es也使用Java开发并使用Lucene作为其核心来实现所有索引和搜索的功能,但是它的目的是通

    2024年01月19日
    浏览(34)
  • ElasticSearch8 - SpringBoot整合ElasticSearch

    springboot 整合 ES 有两种方案,ES 官方提供的 Elasticsearch Java API Client 和 spring 提供的 [Spring Data Elasticsearch](Spring Data Elasticsearch) 两种方案各有优劣 Spring:高度封装,用着舒服。缺点是更新不及时,有可能无法使用 ES 的新 API ES 官方:更新及时,灵活,缺点是太灵活了,基本是一

    2024年03月25日
    浏览(85)
  • 【ElasticSearch系列-05】SpringBoot整合elasticSearch

    ElasticSearch系列整体栏目 内容 链接地址 【一】ElasticSearch下载和安装 https://zhenghuisheng.blog.csdn.net/article/details/129260827 【二】ElasticSearch概念和基本操作 https://blog.csdn.net/zhenghuishengq/article/details/134121631 【三】ElasticSearch的高级查询Query DSL https://blog.csdn.net/zhenghuishengq/article/details/1

    2024年02月06日
    浏览(31)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包