HttpPost请求Elasticsearch

本文介绍了一个用于从Elasticsearch获取和检索数据的Java实用工具类。该工具类包括两个主要功能:一是通过GET请求获取索引模式信息,二是通过POST请求进行数据搜索。文章详细展示了如何设置HTTP请求头、构建请求实体以及处理响应结果。

package com.train.monitoring.Reptile_mobile_monitoring.util;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

public class ESConfig {
    
      public String get(){
          DefaultHttpClient httpClient = new DefaultHttpClient();
          String url="http://101.236.57.141:5601/api/saved_objects/_find?type=index-pattern&per_page=10000";
            HttpGet httpGet = new HttpGet(url);
     
            httpGet.addHeader("Content-Type", "application/json;charset=utf-8");

            // 执行请求
            HttpResponse response=null;
            JSONObject jsonObject=null;
            try {
                response = httpClient.execute(httpGet);
                String json2 = EntityUtils.toString(response.getEntity(), "utf-8");
                jsonObject = JSONObject.parseObject(json2);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
     
            // 打印执行结果
            System.out.println(jsonObject);
          
        return null;
      }
      
      
      public static JSONObject post(String url){
          DefaultHttpClient httpClient = new DefaultHttpClient();
          /**
           * curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
'
           */
//            String url = "http://101.236.47.119:9200/redis-log-2018.07.26/doc/_search?pretty";
            HttpPost httpPost = new HttpPost(url);
     
            // 设置请求的header
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
//            String param="{"+
//                    "\"query\": { \"match_all\": {} },"+
//                    "\"from\": 10,"+
//                    "\"size\": 10"+
//                    "}";
            String param="{"+
                    "\"query\": { \"match_phrase\": {\"biztype\":\"排队的 代理IP为:\"} },"+
                    "\"from\": 1,"+
                    "\"size\": 9000"+
                    "}";
//            String param="{"+
//                    "  \"query\": {"+
//                    "    \"bool\": {"+
//                    "      \"should\": ["+
//                    "        { \"match\": { \"biztype\": \"排队的代理IP为:\" } }"+
//                //    "        { \"match\": { \"address\": \"lane\" } }"+
//                    "      ]"+
//                    "    }"+
//                    "  }"+
//                    "}";
            // 设置请求的参数
            JSONObject jsonParam = JSONObject.parseObject(param);
           
            
            StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            JSONObject jsonObject=null;
            try {
                
                // 执行请求
                HttpResponse response = httpClient.execute(httpPost);
                String json2 = EntityUtils.toString(response.getEntity(), "utf-8");
                jsonObject = JSONObject.parseObject(json2);
            } catch (Exception e) {
                e.printStackTrace();
            }
     
            // 打印执行结果
            return jsonObject;

      }
}
 

### 在 Postman 中通过 POST 请求查询 Elasticsearch 的特定字段并包含账号密码的身份验证 要在 Postman 中通过 POST 请求查询 Elasticsearch 的特定字段,并且包含账号密码的身份验证,可以按照以下方法进行配置。 #### 配置基本身份验证 在 Postman 中,选择请求类型为 `POST`,然后在 `Authorization` 标签下选择 `Basic Auth`。输入 Elasticsearch 的用户名和密码[^1]。Postman 会自动生成正确的 `Authorization` 请求头。 #### 构建查询请求 构建一个 POST 请求,目标 URL 为 Elasticsearch 的 `_search` 端点。例如: ```plaintext http://<your-elasticsearch-host>:<port>/<index-name>/_search ``` 将 `<your-elasticsearch-host>`、`<port>` 和 `<index-name>` 替换为实际的 Elasticsearch 服务地址、端口和索引名称[^1]。 #### 设置请求体 在请求体中,指定需要查询的字段。例如,如果只想获取 `name` 和 `sex` 字段,并且查询条件为 `sex` 等于 `男`,可以使用以下 JSON 格式的请求体: ```json { "_source": ["name", "sex"], "query": { "terms": { "sex": ["男"] } } } ``` 此请求体指定了 `_source` 参数以限制返回的字段,并定义了一个 `terms` 查询来匹配 `sex` 字段为 `男` 的文档[^3]。 #### 示例响应 服务器响应结果可能类似于以下内容: ```json { "took": 5, "timed_out": false, "_shards": { "total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": { "total": 2, "max_score": 1.0, "hits": [ { "_index": "user", "_type": "_doc", "_id": "1", "_score": 1.0, "_source": { "name": "张三", "sex": "男" } }, { "_index": "user", "_type": "_doc", "_id": "2", "_score": 1.0, "_source": { "name": "张三1", "sex": "男" } } ] } } ``` 此响应展示了两个匹配的文档,每个文档仅包含 `name` 和 `sex` 字段[^3]。 #### 使用 `filter_path` 参数优化响应 为了进一步优化响应,只返回所需的字段或错误信息,可以在 URL 中添加 `filter_path` 查询参数。例如: ```plaintext http://<your-elasticsearch-host>:<port>/<index-name>/_search?filter_path=hits.hits._source,hits.total ``` 此 URL 将响应限制为 `hits.hits._source` 和 `hits.total` 字段[^2]。 ###
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值