elasticsearch6.2.4-java-restful-api 插入和获取数据。

插入数据demo

public class Main {
    public static void main(String[] args) throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")).build();
        System.out.println(123);
        Map<String, String> params = Collections.emptyMap();
        for (int i = 1; i <= 1000; i++) {
            System.out.println(" i=" + i + " start ");
            HashMap<String, Object> context = new HashMap<>();
            context.put("pid", i);
            context.put("pdate", new Date());
            context.put("pname", "张三");
            String jsonString = JSON.toJSONString(context);
            HttpEntity entity = new NStringEntity(jsonString, ContentType.APPLICATION_JSON);
            Response response = restClient.performRequest("PUT", "/posts/doc/" + i, params, entity);
            System.out.println(EntityUtils.toString(response.getEntity()));
        }

    }
}

浏览器查看地址:http://118.25.5.23:9200/posts/doc/2

查找数据demo:

public class Get {
    public static void main(String[] args) throws IOException {
        RestClient restClient = RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")).build();

        System.out.println(123);

        Map<String, String> params = new HashMap<>();
        // params.put("pretty", "true");
        // params.put("q", "pid:33");

        HttpEntity entity = new NStringEntity("{\"query\":{\"bool\":{\"filter\":{\"range\":{\"pid\":{\"gt\":997}}}}}}",
                ContentType.APPLICATION_JSON);
        // HttpEntity entity1 = new
        // NStringEntity("{\"query\":{\"match\":{\"pid\":\"33\"}}}",
        // ContentType.APPLICATION_JSON);

        Response response = restClient.performRequest("GET", "/posts/_search", params, entity);

        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    public static Map<String, Object> g() {
        return new HashMap<>();
    }
}

NStringEntity中的字符串是json,格式化后是这样的,意思是查询pid大于997的数据:

{
    "query": {
        "bool": {
            "filter": {
                "range": {
                    "pid": { "gt": 997 } }
            }
        }
    }
}

这里的数据还可以是:

{
  "query": {
    "bool": {
      "filter": {
        "range": {
          "age": { "gt": 20 } }
      },
      "must": {
        "match": {
          "last_name": "Smith" }
      }
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值