Elasticsearch——Java 访问Rest API

作者简介:大家好,我是smart哥,前中兴通讯、美团架构师,现某互联网公司CTO

联系qq:184480602,加我进群,大家一起学习,一起进步,一起对抗互联网寒冬

学习必须往深处挖,挖的越深,基础越扎实!

阶段1、深入多线程

阶段2、深入多线程设计模式

阶段3、深入juc源码解析


阶段4、深入jdk其余源码解析


阶段5、深入jvm源码解析

码哥源码部分

码哥讲源码-原理源码篇【2024年最新大厂关于线程池使用的场景题】

码哥讲源码【炸雷啦!炸雷啦!黄光头他终于跑路啦!】

码哥讲源码-【jvm课程前置知识及c/c++调试环境搭建】

​​​​​​码哥讲源码-原理源码篇【揭秘join方法的唤醒本质上决定于jvm的底层析构函数】

码哥源码-原理源码篇【Doug Lea为什么要将成员变量赋值给局部变量后再操作?】

码哥讲源码【你水不是你的错,但是你胡说八道就是你不对了!】

码哥讲源码【谁再说Spring不支持多线程事务,你给我抽他!】

终结B站没人能讲清楚红黑树的历史,不服等你来踢馆!

打脸系列【020-3小时讲解MESI协议和volatile之间的关系,那些将x86下的验证结果当作最终结果的水货们请闭嘴】

Java 访问Rest API

Elasticsearch提供Rest API,所以可以直接直接使用 HTTP 请求,去操作 Es。HTTP 请求工具,可以使用 Java 自带的 HttpUrlConnection,也可以使用一些 HTTP 请求库,例如 HttpClient、OKHttp、Spring 中的 RestTemplate 都可以。这种方式有一个弊端,就是要自己组装请求参数,自己去解析响应的 JSON。

1、原生Java访问Rest API

在Java中,可以使用java.net包下的URLConnection类来发送HTTP请求。

    //java原生,手动认证后调用_count接口
    @Test
    public void java_auh() throws IOException {
    
        String username = "elastic";
        String password = "123456";
        //构造Authorization
        String auth = username + ":" + password;
        String encodeAuth = Base64.getEncoder().encodeToString(auth.getBytes());
        String authHeader = "Basic " + encodeAuth;
    
        URL url = new URL("http://localhost:9200/bank/_count?pretty=true");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
    
        con.setRequestProperty("Authorization", authHeader);
    
        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    }
    {
      "count" : 1000,
      "_shards" : {
        "total" : 1,
        "successful" : 1,
        "skipped" : 0,
        "failed" : 0
      }
    }

2、HttpClient访问Rest API

示例:访问_search接口

    //basic auth手动编码认证,调用_search接口
    @Test
    public void httpclient_auth1() throws IOException {
        String username = "elastic";
        String password = "123456";
        //构造Authorization
        String auth = username + ":" + password;
        String encodeAuth = Base64.getEncoder().encodeToString(auth.getBytes());
        String authHeader = "Basic " + encodeAuth;
    
        CloseableHttpClient client = HttpClients.custom().build();
        HttpGet httpGet = new HttpGet("http://localhost:9200/bank/_search");
        httpGet.setHeader("Authorization", authHeader);
        CloseableHttpResponse response = client.execute(httpGet);
    
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            //获取实体内容
            HttpEntity entity = response.getEntity();
            //注意设置编码
            String entityString = EntityUtils.toString(entity, "utf8");
            //输出内容
            System.out.println(entityString);
            EntityUtils.consume(response.getEntity());//消耗实体
        }
    }
    {"took":8,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":1000,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"bank","_type":"_doc","_id":"1","_score":1.0,"_source":{"account_number":1,"balance":39225,"firstname":"Amber","lastname":"Duke","age":32,"gender":"M","address":"880 Holmes Lane","employer":"Pyrami","email":"amberduke@pyrami.com","city":"Brogan","state":"IL"}},{"_index":"bank","_type":"_doc","_id":"6","_score":1.0,"_source":{"account_number":6,"balance":5686,"firstname":"Hattie","lastname":"Bond","age":36,"gender":"M","address":"671 Bristol Street","employer":"Netagy","email":"hattiebond@netagy.com","city":"Dante","state":"TN"}},{"_index":"bank","_type":"_doc","_id":"13","_score":1.0,"_source":{"account_number":13,"balance":32838,"firstname":"Nanette","lastname":"Bates","age":28,"gender":"F","address":"789 Madison Street","employer":"Quility","email":"nanettebates@quility.com","city":"Nogal","state":"VA"}},{"_index":"bank","_type":"_doc","_id":"18","_score":1.0,"_source":{"account_number":18,"balance":4180,"firstname":"Dale","lastname":"Adams","age":33,"gender":"M","address":"467 Hutchinson Court","employer":"Boink","email":"daleadams@boink.com","city":"Orick","state":"MD"}},{"_index":"bank","_type":"_doc","_id":"20","_score":1.0,"_source":{"account_number":20,"balance":16418,"firstname":"Elinor","lastname":"Ratliff","age":36,"gender":"M","address":"282 Kings Place","employer":"Scentric","email":"elinorratliff@scentric.com","city":"Ribera","state":"WA"}},{"_index":"bank","_type":"_doc","_id":"25","_score":1.0,"_source":{"account_number":25,"balance":40540,"firstname":"Virginia","lastname":"Ayala","age":39,"gender":"F","address":"171 Putnam Avenue","employer":"Filodyne","email":"virginiaayala@filodyne.com","city":"Nicholson","state":"PA"}},{"_index":"bank","_type":"_doc","_id":"32","_score":1.0,"_source":{"account_number":32,"balance":48086,"firstname":"Dillard","lastname":"Mcpherson","age":34,"gender":"F","address":"702 Quentin Street","employer":"Quailcom","email":"dillardmcpherson@quailcom.com","city":"Veguita","state":"IN"}},{"_index":"bank","_type":"_doc","_id":"37","_score":1.0,"_source":{"account_number":37,"balance":18612,"firstname":"Mcgee","lastname":"Mooney","age":39,"gender":"M","address":"826 Fillmore Place","employer":"Reversus","email":"mcgeemooney@reversus.com","city":"Tooleville","state":"OK"}},{"_index":"bank","_type":"_doc","_id":"44","_score":1.0,"_source":{"account_number":44,"balance":34487,"firstname":"Aurelia","lastname":"Harding","age":37,"gender":"M","address":"502 Baycliff Terrace","employer":"Orbalix","email":"aureliaharding@orbalix.com","city":"Yardville","state":"DE"}},{"_index":"bank","_type":"_doc","_id":"49","_score":1.0,"_source":{"account_number":49,"balance":29104,"firstname":"Fulton","lastname":"Holt","age":23,"gender":"F","address":"451 Humboldt Street","employer":"Anocha","email":"fultonholt@anocha.com","city":"Sunriver","state":"RI"}}]}}

示例:访问_analyze接口

    //使用CredentialsProvider认证,调用 _analyze接口
    @Test
    public void httpclient_auth2() throws IOException {
        String url = "http://localhost:9200/_analyze?pretty=true";
    
        CloseableHttpClient httpClient = HttpClients.createDefault();
    
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("DataEncoding", "UTF-8");
    
        JSONObject object = new JSONObject();
        object.put("analyzer","ik_smart");
        object.put("text", "我是中国人");
        httpPost.setEntity(new StringEntity(object.toString(), "UTF-8"));
    
    
        // 加es身份认证
        HttpHost targetHost = new HttpHost("192.168.1.1", 9200, "http");
        //设置账号密码
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials("elastic", "123456"));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
    
        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthCache(authCache);
    
        CloseableHttpResponse response = httpClient.execute(httpPost, context);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            //获取实体内容
            HttpEntity entity = response.getEntity();
            //注意设置编码
            String entityString = EntityUtils.toString(entity, "utf8");
            //输出内容
            System.out.println(entityString);
            EntityUtils.consume(response.getEntity());//消耗实体
        }
    }
    {
      "tokens" : [
        {
          "token" : "我",
          "start_offset" : 0,
          "end_offset" : 1,
          "type" : "CN_CHAR",
          "position" : 0
        },
        {
          "token" : "是",
          "start_offset" : 1,
          "end_offset" : 2,
          "type" : "CN_CHAR",
          "position" : 1
        },
        {
          "token" : "中国人",
          "start_offset" : 2,
          "end_offset" : 5,
          "type" : "CN_WORD",
          "position" : 2
        }
      ]
    }

3、使用RestTemplate访问Rest API

    @SpringBootApplication
    public class AppApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(AppApplication.class, args);
        }
    
        @Bean
        public RestTemplate restTemplate(RestTemplateBuilder builder) {
            return builder.build();
        }
    }
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = {AppApplication.class})
    public class RestTemplateTest {
    
        @Autowired
        RestTemplate restTemplate;
    
    
        @Test
        public void restTemplate_auth() {
            String username = "elastic";
            String password = "123456";
            //构造Authorization
            String auth = username + ":" + password;
            String encodeAuth = Base64.getEncoder().encodeToString(auth.getBytes());
            String authHeader = "Basic " + encodeAuth;
    
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", authHeader);
            HttpEntity entity = new HttpEntity(headers);
            ResponseEntity<String> response = restTemplate.exchange("http://localhost:9200/bank/_mappings?pretty=true",
                    HttpMethod.GET,
                    entity,
                    String.class);
            if (response.getStatusCode() == HttpStatus.OK){
                System.out.println(response.getBody());
            }
        }
    }
    {
      "bank" : {
        "mappings" : {
          "properties" : {
            "account_number" : {
              "type" : "long"
            },
            "address" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            },
            "age" : {
              "type" : "long"
            },
            "balance" : {
              "type" : "long"
            },
            "city" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            },
            "email" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            },
            "employer" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            },
            "firstname" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            },
            "gender" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            },
            "lastname" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            },
            "state" : {
              "type" : "text",
              "fields" : {
                "keyword" : {
                  "type" : "keyword",
                  "ignore_above" : 256
                }
              }
            }
          }
        }
      }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值