Java操作Elasticsearch(新增数据)

天行健,君子以自强不息;地势坤,君子以厚德载物。


每个人都有惰性,但不断学习是好好生活的根本,共勉!


文章均为学习整理笔记,分享记录为主,如有错误请指正,共同学习进步。

文章目录


一、服务安装参考

首先需要准备好elasticsearch和kibana

elasticsearch的下载、安装、使用可参考:Elasticsearch安装

kibana的下载、安装、使用可参考:Kibana安装、配置

服务的启动使用和数据增删改查可参考:kibana操作elasticsearch(增删改查)

在进行一下Java实现之前,先将es服务和kibana服务启动

二、Java实现新增数据到ES

Elasticsearch的服务开启后,可以使用http请求进行调用接口来操作Elasticsearch数据

请求的url格式如下:

java 复制代码
http://localhost:9200/index/type/id

对于Java来说,可以使用http请求工具进行实现,同时传参,参数为json类型数据

具体实现如下

1. 环境

并非要求,只是我这里使用的这个环境

JDK 1.8

Maven 3.9.4

IDEA 2023.2.1

2. 包结构

这里主要用到三个文件:pom引入依赖,HttpClientUtils是请求工具,EsHttpRequestController是请求调用测试

3. 依赖引入

引入http工具所需要的依赖,也就是实现请求的依赖

传入的参数为json类型所以也需要json工具的依赖

pom.xml完整内容

java 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.es</groupId>
    <artifactId>ES-HTTP</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.14</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
        <!--json工具-->
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.33</version>
        </dependency>

    </dependencies>


</project>

4. http请求工具

HttpClientUtils.java

java 复制代码
package com.es.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @ClassDescription:
 * @JdkVersion: 1.8
 * @Author: 李白
 * @Created: 2023/10/16 16:12
 */
public class HttpClientUtils {

    public static void post(){

    }
    public static String doPost(String url, String str, String encoding) {
        String body = "";
        try {
            // 创建httpclient对象
            CloseableHttpClient client = HttpClients.createDefault();
            // 创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);
            // 设置参数到请求对象中
            httpPost.setEntity(new StringEntity(str, encoding));
            // 设置header信息
            // 指定报文头【Content-type】、【User-Agent】
            httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
            // 执行请求操作,并拿到结果(同步阻塞)
            CloseableHttpResponse response = client.execute(httpPost);
            // 获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // 按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
            // 释放链接
            response.close();
            return body;
        } catch (Exception e1) {
            e1.printStackTrace();
            return "";

        }
    }

}

5. 测试代码

编写mian方法执行请求存数据到es

EsHttoRequestController.java

java 复制代码
package com.es.test;

import com.alibaba.fastjson2.JSONObject;
import com.es.utils.HttpClientUtils;

/**
 * @ClassDescription:
 * @JdkVersion: 1.8
 * @Author: 李白
 * @Created: 2023/10/16 16:12
 */
public class EsHttpRequestController {

    public static void main(String[] args) {
        JSONObject js = new JSONObject();
        js.put("name","杜甫");
        js.put("age","6800");
        js.put("gender","男");
        String jsonStr = js.toJSONString();
        HttpClientUtils.doPost("http://127.0.0.1:9200/deviceinfo/users/1002",jsonStr,"UTF-8");
    }

}

6. 访问kibana服务

先看kibana服务查看数据

打开侧边栏,Analytics--Discover

查看现有数据

执行5. 测试代码的代码,然后刷新界面查看新增数据

如下,新增成功


感谢阅读,祝君暴富!

相关推荐
Amumu1213810 小时前
TypeScript学习: 进阶知识
开发语言·学习·typescript
炸薯条!11 小时前
Python基础学习:文件操作详解(打开、读取、写入与路径)
java·服务器·python
Dreams_l11 小时前
基于SpringBoot实现的抽奖系统(四)
java·spring boot·后端
这个昵称不容易11 小时前
SpringBoot 网上订餐系统设计与实现:80 个 Java 文件、91 个接口,附真实运行截图
java·springboot·毕设
Helix25011 小时前
JDK异常处理最佳实践:受检异常、非受检异常、try-catch-finally与全局异常处理完整指南
java·开发语言·jdk·异常处理·全局异常·自定义异常·try-catch
时间的情敌12 小时前
Three.js 后处理辉光 Bloom、告警发光效果、管线流光、着色器流动管线(ShaderMaterial)
开发语言·javascript·three.js·着色器
Evand J13 小时前
【CIR系列2】UWB视距(LOS)与非视距(NLOS)信道冲激响应(CIR)建模与对比,MATLAB
开发语言·matlab·信号处理·nlos·cir
风落青芜13 小时前
C++入门:类和对象(二)
开发语言·数据结构·c++·算法
向科→向总工→空间动态计系统13 小时前
机器人大脑系统
开发语言·人工智能·python·机器人
一只QAQ13 小时前
c语言八股
c语言·开发语言