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" }
      }
    }
  }
}

猜你喜欢

转载自blog.csdn.net/faicm/article/details/80169185