【工具类】Elasticsearch的HTTP客户端(Java)

一、介绍

1. 原理

Java基于Http请求操作ES,与Kibana上的操作一致。

Kibana上的dsl与Http的关系:

  • GET、POST等同于HTTP的POST
  • PUT 等同于HTTP的PUT
  • DELETE 等同于HTTP的DELETE

如图
在这里插入图片描述
该DSL可转化为HTTP请求(注意port为http端口,默认为9200)

POST ip:port/docwrite/_search

请求体为:

{
  "query": {
    "match": {
      "attachment.content": "Seata"
    }
  }
}

2. 对比

已有客户端的缺点:

  • 客户端繁多,语法不一,学习成本高。写完DSL语句后需要根据语法进行转换
  • 客户端版本一致性要求高,同一客户端版本变更后类变化大
  • 部分接口高版本不支持。比如DSL可以使用ingest抽取数据,但是7.20以后的Java客户端不支持

HTTP客户端的优点:

  • DSL即代码,写完DSL后可以放到json文件中直接调用,直观
  • DSL可以实现的,HTTP客户端就可以实现,不受已有客户端版本的影响
  • 无学习成本,返回数据处理灵活

二、使用

// 读取Resource/elasticsearch/QueryArea.json的json数据,即DSL的请求体
 JsonNode jsonNode = JsonFileUtils.readFileToJson("/elasticsearch/QueryArea.json");
// 执行查询语句。result与Kibana的DSL查询结果一致
JsonNode result = elasticsearchRequestUtils.post("/" + indexName + "/_search", jsonNode);

三、源码

Json文件的读取依赖该工具类

  1. 添加配置文件
elasticsearch:
  host: 
  # 这里要配置HTTP端口
  port: 9200
  username: 
  password: 
  # 下面三个暂时没用上,后续可能更新
  connTimeout: 3000
  socketTimeout: 5000
  connectionRequestTimeout: 500
  1. 配置文件实体类
@Data
public class EsConfig {
    protected String host;
    protected int port;
    protected int connTimeout;
    protected int socketTimeout;
    protected int connectionRequestTimeout;
    protected String username;
    protected String password;
}
  1. 请求工具类
package com.dreambyday.http;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


/**
 * <p> Description:ElasticsearchRequestUtils</p>
 * <p> CreationTime: 2022/10/27 21:09
 *
 * @author dreambyday
 * @since 1.0
 */
public class ElasticsearchRequestUtils {
    private final RestTemplate restTemplate;
    private final String prefix;
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    private final EsConfig esConfig;
    public ElasticsearchRequestUtils(EsConfig esConfig) {
        prefix = "http://" + esConfig.getHost() + ":" + esConfig.getPort();
        this.esConfig = esConfig;
        restTemplate = new RestTemplate();
    }


    /**
     *
     * @param uri uri
     * @param jsonNode 请求体
     * @param <T> com.fasterxml.jackson.databind.JsonNode;com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>
     * @return 响应body
     */
    public <T>JsonNode post(String uri, T jsonNode) throws JsonProcessingException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBasicAuth(esConfig.getUsername(), esConfig.getPassword());
        HttpEntity<T> request = new HttpEntity<>(jsonNode, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(prefix + uri, request, String.class);
        String body = response.getBody();
        return OBJECT_MAPPER.readTree(body);
    }

    public <T>void delete(String uri) throws JsonProcessingException {
        restTemplate.delete(prefix + uri);
    }

    /**
     *
     * @param uri uri
     * @param jsonNode 请求体
     * @param <T> com.fasterxml.jackson.databind.JsonNode;com.fasterxml.jackson.core.type.TypeReference<Map<String, Object>>
     */
    public <T>void put(String uri, T jsonNode) throws JsonProcessingException {
        HttpHeaders headers = new HttpHeaders();
        headers.setBasicAuth(esConfig.getUsername(), esConfig.getPassword());
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<T> request = new HttpEntity<>(jsonNode, headers);
        restTemplate.put(prefix + uri, request);
    }
    public JsonNode get(String uri){
        ResponseEntity<JsonNode> response = restTemplate.getForEntity(prefix + uri, JsonNode.class);
        return response.getBody();
    }
}
  1. 配置类
@Configuration
public class ElasticsearchRequestConfiguration {
    @Bean
    @ConfigurationProperties(prefix = "elasticsearch")
    public EsConfig esConfig() {
        return new EsConfig();
    }
    @Bean
    ElasticsearchRequestUtils elasticsearchRequestUtils() {
        return new ElasticsearchRequestUtils(esConfig());
    }
}

Elasticsearch是一个开源的分布式搜索和分析引擎,它被广泛应用于全文搜索、日志分析、数据可视化等领域。Elasticsearch提供了丰富的API和功能,可以方便地进行数据索引、搜索、聚合和分析。 在使用Elasticsearch时,可以使用Java编写工具类来简化与Elasticsearch的交互。下面是一个简单的Elasticsearch工具类的示例: ```java import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; import java.io.IOException; public class ElasticsearchUtils { private RestHighLevelClient client; public ElasticsearchUtils() { client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http"))); } public SearchResponse search(String index, String field, String keyword) throws IOException { SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchQuery(field, keyword)); sourceBuilder.sort(field, SortOrder.DESC); SearchRequest searchRequest = new SearchRequest(index); searchRequest.source(sourceBuilder); return client.search(searchRequest, RequestOptions.DEFAULT); } public void close() throws IOException { client.close(); } } ``` 上述示例中的工具类使用了ElasticsearchJava高级客户端(RestHighLevelClient)来与Elasticsearch进行交互。其中,`search`方法用于执行搜索操作,`close`方法用于关闭与Elasticsearch的连接。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值