首页 > 编程语言 >2.Java API操作elasticsearch

2.Java API操作elasticsearch

时间:2022-11-03 21:57:43浏览次数:42  
标签:Java client public API elasticsearch user new RestHighLevelClient response

新建Maven工程

添加依赖:

<dependencies>
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>7.8.0</version>
    </dependency>
    <!-- elasticsearch 的客户端 -->
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.8.0</version>
    </dependency>
    <!-- elasticsearch 依赖 2.x 的 log4j -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.8.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.8.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.9</version>
    </dependency>
    <!-- junit 单元测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

客户端连接:

public class ESTest_Client {
    public static void main(String[] args) throws IOException {
        // 创建客户端对象,高级别客户端,你需要连接服务器,需要知道ip端口号,访问方式
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));
        //业务逻辑
        System.out.println(client);
        // 关闭客户端连接
        client.close();
    }
}

4.2 索引操作

4.2.1 创建索引

public static void main(String[] args) throws IOException {
        // 创建客户端对象,高级别客户端,你需要连接服务器,需要知道ip端口号,访问方式
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));
        //业务逻辑
        System.out.println(client);
        // 创建索引,先拿到索引,然后创建,第一个参数是请求对象,后面是选项
        CreateIndexRequest request = new CreateIndexRequest("user");//索引名称
        // 发完请求,就会有响应
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);// 默认请求配置
        // 响应的状态
        boolean acknowledged = response.isAcknowledged();
        //输出true
        System.out.println(acknowledged);
        // 关闭客户端连接
        client.close();
    }

查询所有索引发现索引创建成功!

 

4.2.2 索引查询

public class ESTest_Index_Search {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 查询索引
        GetIndexRequest request = new GetIndexRequest("user");
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
        // 别名操作
        System.out.println(response.getAliases());
        // 结构
        System.out.println(response.getMappings());
 
        client.close();
    }
}

输出:

{user=[]}
{user=org.elasticsearch.cluster.metadata.MappingMetadata@e2704661}

4.2.3 索引删除

public class DeleteIndex {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));
        // 删除索引 - 请求对象
        DeleteIndexRequest request = new DeleteIndexRequest("user");
        // 发送请求,获取响应
        AcknowledgedResponse response = client.indices().delete(request,RequestOptions.DEFAULT);
        // 操作结果
        System.out.println("操作结果 : " + response.isAcknowledged());
        client.close();
    }
}

 输出true:

 

4.3 文档操作

4.3.1 新建实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private String sex;
    private Integer age;
}

4.3.2 插入数据

public class ESTest_Doc_Insert {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));
 
        // 插入数据,这里需要的是index
        IndexRequest indexRequest = new IndexRequest();
        // 索引名字,索引的id
        indexRequest.index("user").id("1001");
        User user = new User();
        user.setName("zhangsan");
        user.setAge(30);
        user.setSex("男");
        // 向ES插入数据,必须将数据转换为json格式
        ObjectMapper mapper = new ObjectMapper();
        String value = mapper.writeValueAsString(user);
        // 放到请求体中
        indexRequest.source(value, XContentType.JSON);
        IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
        //输出:CREATED 
        System.out.println(response.getResult());

        client.close();
    }
}

postman获取文档,发现其已经创建成功!

 

4.3.3 修改数据

public class ESTest_Doc_Update {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));
        //修改数据
        UpdateRequest request=new UpdateRequest();
        request.index("user").id("1001");
        request.doc(XContentType.JSON,"sex","女");
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        //输出:UPDATED
        System.out.println(response.getResult());
        client.close();
    }
}

 

4.3.4 查询数据

/**
 * 查询数据
 */
public class ESTest_Doc_Query {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));
        GetRequest request=new GetRequest().index("user").id("1001");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //打印信息
        System.out.println("_index:" + response.getIndex());
        System.out.println("_type:" + response.getType());
        System.out.println("_id:" + response.getId());
        System.out.println("source:" + response.getSourceAsString());
    }
}

输出:

_index:user
_type:_doc
_id:1001
source:{"name":"zhangsan","sex":"女","age":30}

4.3.5 数据删除

/**
 * 删除数据
 */
public class ESTest_Doc_Delete {
    public static void main(String[] args) throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));
        //创建请求对象
        DeleteRequest request = new DeleteRequest().index("user").id("1001");
        //客户端发送请求,获取响应对象
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        //打印信息
        System.out.println(response.toString());
    }
}

输出:

DeleteResponse[index=user,type=_doc,id=1001,version=3,result=deleted,shards=ShardInfo{total=2, successful=1, failures=[]}]

标签:Java,client,public,API,elasticsearch,user,new,RestHighLevelClient,response
From: https://www.cnblogs.com/wmd-l/p/16855971.html

相关文章

  • 如何利用API FOX编写业务测试用例?
     假设管理员进行一个场景:为网站新增品牌,内容为品牌名:冬青及服务商名:胡歌,并验证是否新增成功所以:通过页面的F12查询,我们可以知道新增品牌接口,及列表品牌接口,以及品牌详情......
  • Java学习笔记day3--二维数组
    packageday4_array;importjavax.swing.plaf.synth.SynthFormattedTextFieldUI;//一维数组的元素仍然是一维数组,则构成了二维数组publicclassArrayDemension2{......
  • 狂神说java基础——面向对象编程
    面向对象编程(oop)1、什么是面向对象(00)面向过程:线性思维面向对象:分类思维​ 本质:以类的方式组织代码,以对象的形式阻止(封装)数据三大特性:封装,继承,多态2、回顾方......
  • Java集合精选常见面试题
    前言博主只是这篇文章的搬运工,为了加强记忆自己梳理了一遍并扩展了部分内容。集合拓展链接:集合概述&集合之Collection接口-至安-博客园(cnblogs.com)Java集合概览......
  • Java基础面试题整理
    一、何为面向对象面向对象简单来说就是一种编程方式,也可以说是一种思维方式,面向对象会注重一件事情的参与者(对象)、以及各自需要做什么动作。而面向过程则是更注重一件事情......
  • 实验七:基于REST API的SDN北向应用实践
    一、实验目的1.能够编写程序调用OpenDaylightRESTAPI实现特定网络功能;2.能够编写程序调用RyuRESTAPI实现特定网络功能。二、实验环境1.下载虚拟机软件OracleVisua......
  • JavaEE#JCA
    概述jca依赖jta,也就是javax.resource-api依赖javax.transation-api。javax.resourcejavax.resource.ccijavax.resource.spijavax.resource.spi.endpointjavax.resource.......
  • 如何写一个给自己的框架写一个优雅的Java Config模块
    发博词工作时间长一点的工程师,平时的“工作生活”中肯定免不了写一些大大小小的框架和中间件。最近在看SpringSecurity的源码,由于这个框架要解决的问题比较多、复杂且零碎,......
  • 实验7:基于REST API的SDN北向应用实践
    实验目的能够编写程序调用OpenDaylightRESTAPI实现特定网络功能;能够编写程序调用RyuRESTAPI实现特定网络功能。实验要求(一)基本要求编写Python程序,调用OpenDayligh......
  • JAVA中输入数字,然后再逆序输出来
    一、问题描述:就是我们现在输入一些数字,然后我们将输入的数字,倒着再输出出来。实现代码如下:importjava.util.Scanner;publicclassni_sort{publicstaticvoid......