elasticsearch 操作Demo



引入maven依赖

    org.elasticsearch.client
    rest
    5.5.0


    junit
    junit
    4.12


    com.google.code.gson
    gson
    2.2.4


    commons-io
    commons-io
    2.5



public class ElTest {

    private static RestClient restClient;

    private static Gson gson = new Gson();
    /**
 * 初始化RestClient
 */
 @Before
 public void initRestClient(){
         restClient = RestClient.builder(
                new HttpHost("139.199.119.214", 9200, "http")).build();
    }


    /**
 * 创建索引(id自己设置,PUT请求)
 */
 @Test
 public void testCreateIndex() throws Exception{
        User user = new User();
        user.setId(100L);
        user.setAge(20);
        user.setName("张三100");
        user.setSex(1);

        HttpEntity entity = new NStringEntity(gson.toJson(user), ContentType.APPLICATION_JSON);

        Response indexResponse = restClient.performRequest(
                "PUT",
                "userindex/user/100",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(indexResponse.getEntity()));
    }

    /**
 * 创建索引(id自动生成,POST请求)
 */
 @Test
 public void testCreateIndex2() throws Exception{
        User user = new User();
        user.setAge(20);
        user.setName("张三");
        user.setSex(1);

        HttpEntity entity = new NStringEntity(gson.toJson(user), ContentType.APPLICATION_JSON);

        Response indexResponse = restClient.performRequest(
                "POST",
                "userindex/user/",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(indexResponse.getEntity()));
    }

    /**
 * 根据id查询
 * @throws Exception
 */
 @Test
 public void testFindById() throws Exception{
            String DSL ="{\n" +
                " \"query\": {\n" +
                " \"match\" : {\n" +
                " \"id\" : \"100\"\n" +
                " }\n" +
                " }\n" +
                "}";
            HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
            Response response = restClient.performRequest(
                    "GET",
                    "userindex/user/_search",
                    Collections.emptyMap(),
                    entity);
        System.out.println(EntityUtils.toString(response.getEntity()));

        InputStream content = response.getEntity().getContent();
        System.out.println("@@@liu"+content.toString());
        Header[] headers = response.getHeaders();
        for (Header header:headers){
            System.out.println("@@@name"+header.getName());
            System.out.println("@@@value"+header.getValue());
        }


        /*byte[] b = new byte[1024];
 int lenth = 0;
 while ((lenth=content.read())!=-1){
 int read = content.read(b, 0, lenth);
 System.out.println("!!!"+new String(b,0,read));
 }*/
 System.out.println("!!!"+IOUtils.toString(content,"UTF-8"));
    }

    /**
 * (查询特定字段用户)
 * @throws Exception
 */
 @Test
 public void testFindByKey() throws Exception{
        String DSL ="{\n" +
                " \"query\": {\n" +
                " \"match\" : {\n" +
                " \"name\" : \"张1\"\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "GET",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));

    }

    /**
 * 查询所有(默认返回10条记录)
 */
 @Test
 public void findAll() throws Exception{
        String DSL = "{\n" +
                " \"query\": { \"match_all\": {} }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "GET",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));

    }

    /**
 * match_all & 返回11到20个文档信息
 * from:指定文档索引从哪里开始,默认从0开始
 size:从from开始,返回多个文档
 */
 @Test
 public void findByPage() throws Exception{
        String DSL = "{\n" +
                " \"query\": { \"match_all\": {} },\n" +
                " \"from\": 10,\n" +
                " \"size\": 10\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));

    }

    /**
 * 根据年龄降序排序查询.默认返回10条
 */
 @Test
 public void findAllByAgeOderBy() throws Exception{
        String DSL = "{\n" +
                " \"query\": { \"match_all\": {} },\n" +
                " \"sort\": { \"age\": { \"order\": \"desc\" } }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 查询返回指定的字段(这样操作有点类似于SQL SELECT FROM field lis)
 */
 @Test
 public void findByLimitField() throws Exception{
        String DSL = "{\n" +
                " \"query\": { \"match_all\": {} },\n" +
                " \"_source\": [\"name\", \"age\"]\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }


    /**
 * 布尔值(bool)查询(返回 匹配name=张1 & age=21)
 */
 @Test
 public void findByMustBool() throws Exception{
        String DSL = "{\n" +
                " \"query\": {\n" +
                " \"bool\": {\n" +
                " \"must\": [\n" +
                " { \"match\": { \"name\": \"张1\" } },\n" +
                " { \"match\": { \"age\": \"21\" } }\n" +
                " ]\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 布尔值(bool)查询(返回 匹配name=张1 || age=21)
 */
 @Test
 public void findByOrBool() throws Exception{
        String DSL = "{\n" +
                " \"query\": {\n" +
                " \"bool\": {\n" +
                " \"should\": [\n" +
                " { \"match\": { \"name\": \"张1\" } },\n" +
                " { \"match\": { \"age\": \"21\" } }\n" +
                " ]\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }
    /**
 * 布尔值(bool)查询(返回 不匹配name=张1 & age=21)
 */
 @Test
 public void findByMachNotBool() throws Exception{
        String DSL = "{\n" +
                " \"query\": {\n" +
                " \"bool\": {\n" +
                " \"must_not\": [\n" +
                " { \"match\": { \"name\": \"张1\" } },\n" +
                " { \"match\": { \"age\": \"21\" } }\n" +
                " ]\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 布尔值(bool)查询(返回 name=张1 & age!=21)
 */
 @Test
 public void findByMachAndNotBool() throws Exception{
        String DSL = "{\n" +
                " \"query\": {\n" +
                " \"bool\": {\n" +
                " \"must\": [\n" +
                " { \"match\": { \"name\": \"张1\" } }\n" +
                " ],\n" +
                " \"must_not\": [\n" +
                " { \"match\": { \"age\": \"21\" } }\n" +
                " ]\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }


    /**
 * 范围查询(age在25到28岁之间)
 */
 @Test
 public void findByRang() throws Exception{
        String DSL = "{\n" +
                " \"query\": {\n" +
                " \"range\" : {\n" +
                " \"age\" : {\n" +
                " \"gte\" : 25,\n" +
                " \"lte\" : 28,\n" +
                " \"boost\" : 2.0\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "GET",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 分组查询(按年龄分组查询,降序统计top 10)
 *类似 SELECT age, COUNT(*) FROM user GROUP BY age ORDER BY COUNT(*) DESC
 */
 @Test
 public void findByGroup() throws Exception{
        String DSL = "{\n" +
                " \"size\": 0,\n" +
                " \"aggs\": {\n" +
                " \"group_by_age\": {\n" +
                " \"terms\": {\n" +
                " \"field\": \"age\"\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 分组查询(按年龄分组查询,查询组里其他字段的平均值)
 *类似 SELECT age, avg(age) FROM user GROUP BY age ORDER BY COUNT(*) DESC
 */
 @Test
 public void findByGroupAndAvag() throws Exception{
        String DSL = "{\n" +
                " \"size\": 0,\n" +
                " \"aggs\": {\n" +
                " \"group_by_age\": {\n" +
                " \"terms\": {\n" +
                " \"field\": \"age\"\n" +
                " },\n" +
                " \"aggs\": {\n" +
                " \"average_age\": {\n" +
                " \"avg\": {\n" +
                " \"field\": \"age\"\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 分组查询(按年龄分组查询,并且降序排序)
 *类似 SELECT age, avg(age) FROM user GROUP BY age ORDER BY avg(age) DESC
 */
 @Test
 public void findByGroupAndOrderBy() throws Exception{
        String DSL = "{\n" +
                " \"size\": 0,\n" +
                " \"aggs\": {\n" +
                " \"group_by_age\": {\n" +
                " \"terms\": {\n" +
                " \"field\": \"age\",\n" +
                " \"order\": {\n" +
                " \"average_age\": \"desc\"\n" +
                " }\n" +
                " },\n" +
                " \"aggs\": {\n" +
                " \"average_age\": {\n" +
                " \"avg\": {\n" +
                " \"field\": \"age\"\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }


    /**
 * 删除操作
 */
 @Test
 public void testDelete() throws Exception{
        Response response = restClient.performRequest(
                "DELETE",
                "userindex/user/100",
                Collections.emptyMap());
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 根据条件删除(使用_delete_by_query,POST请求)
 */
 @Test
 public void testDeleteByQuery()throws Exception{
        String DSL ="{\n" +
                " \"query\": {\n" +
                " \"match\" : {\n" +
                " \"name\" : \"张1\"\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_delete_by_query",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }


    /**
 * 跟新操作(1. 从旧文档中检索JSON
 2. 修改它
 3. 删除旧文档
 4. 索引新文档)
 */
 @Test
 public void testUpdate() throws Exception{
        User user = new User();
        user.setId(100L);
        user.setAge(20);
        user.setName("张三修改");
        user.setSex(1);

        HttpEntity entity = new NStringEntity(gson.toJson(user), ContentType.APPLICATION_JSON);

        Response indexResponse = restClient.performRequest(
                "PUT",
                "userindex/user/100",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(indexResponse.getEntity()));
    }


    /**
 * 局部跟新字段(动态添加字段,添加tags和views字段)
 */
 @Test
 public void testUpdateField() throws Exception{
        String DSL ="{\n" +
                " \"doc\" : {\n" +
                " \"tags\" : [ \"testing\" ],\n" +
                " \"views\": 0\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/100/_update",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 使用脚本部分跟新字段(将views字段数量加1)
 */
 @Test
 public void testUpdateFieldByScript() throws Exception{
        String DSL ="{\n" +
                " \"script\" : \"ctx._source.views+=1\"\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/100/_update",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 将search 标签追加到 tags 数组中
 */
 @Test
 public void testUpdateFieldAddByScript() throws Exception{
        String DSL = "{\n" +
                " \"script\" : \"ctx._source.tags+=new_tag\",\n" +
                " \"params\" : {\n" +
                " \"new_tag\" : \"search\"\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/100/_update",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }


    @After
 public void closeRestClient() throws Exception{
        restClient.close();
    }


}

引入maven依赖

    org.elasticsearch.client
    rest
    5.5.0


    junit
    junit
    4.12


    com.google.code.gson
    gson
    2.2.4


    commons-io
    commons-io
    2.5



public class ElTest {

    private static RestClient restClient;

    private static Gson gson = new Gson();
    /**
 * 初始化RestClient
 */
 @Before
 public void initRestClient(){
         restClient = RestClient.builder(
                new HttpHost("139.199.119.214", 9200, "http")).build();
    }


    /**
 * 创建索引(id自己设置,PUT请求)
 */
 @Test
 public void testCreateIndex() throws Exception{
        User user = new User();
        user.setId(100L);
        user.setAge(20);
        user.setName("张三100");
        user.setSex(1);

        HttpEntity entity = new NStringEntity(gson.toJson(user), ContentType.APPLICATION_JSON);

        Response indexResponse = restClient.performRequest(
                "PUT",
                "userindex/user/100",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(indexResponse.getEntity()));
    }

    /**
 * 创建索引(id自动生成,POST请求)
 */
 @Test
 public void testCreateIndex2() throws Exception{
        User user = new User();
        user.setAge(20);
        user.setName("张三");
        user.setSex(1);

        HttpEntity entity = new NStringEntity(gson.toJson(user), ContentType.APPLICATION_JSON);

        Response indexResponse = restClient.performRequest(
                "POST",
                "userindex/user/",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(indexResponse.getEntity()));
    }

    /**
 * 根据id查询
 * @throws Exception
 */
 @Test
 public void testFindById() throws Exception{
            String DSL ="{\n" +
                " \"query\": {\n" +
                " \"match\" : {\n" +
                " \"id\" : \"100\"\n" +
                " }\n" +
                " }\n" +
                "}";
            HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
            Response response = restClient.performRequest(
                    "GET",
                    "userindex/user/_search",
                    Collections.emptyMap(),
                    entity);
        System.out.println(EntityUtils.toString(response.getEntity()));

        InputStream content = response.getEntity().getContent();
        System.out.println("@@@liu"+content.toString());
        Header[] headers = response.getHeaders();
        for (Header header:headers){
            System.out.println("@@@name"+header.getName());
            System.out.println("@@@value"+header.getValue());
        }


        /*byte[] b = new byte[1024];
 int lenth = 0;
 while ((lenth=content.read())!=-1){
 int read = content.read(b, 0, lenth);
 System.out.println("!!!"+new String(b,0,read));
 }*/
 System.out.println("!!!"+IOUtils.toString(content,"UTF-8"));
    }

    /**
 * (查询特定字段用户)
 * @throws Exception
 */
 @Test
 public void testFindByKey() throws Exception{
        String DSL ="{\n" +
                " \"query\": {\n" +
                " \"match\" : {\n" +
                " \"name\" : \"张1\"\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "GET",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));

    }

    /**
 * 查询所有(默认返回10条记录)
 */
 @Test
 public void findAll() throws Exception{
        String DSL = "{\n" +
                " \"query\": { \"match_all\": {} }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "GET",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));

    }

    /**
 * match_all & 返回11到20个文档信息
 * from:指定文档索引从哪里开始,默认从0开始
 size:从from开始,返回多个文档
 */
 @Test
 public void findByPage() throws Exception{
        String DSL = "{\n" +
                " \"query\": { \"match_all\": {} },\n" +
                " \"from\": 10,\n" +
                " \"size\": 10\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));

    }

    /**
 * 根据年龄降序排序查询.默认返回10条
 */
 @Test
 public void findAllByAgeOderBy() throws Exception{
        String DSL = "{\n" +
                " \"query\": { \"match_all\": {} },\n" +
                " \"sort\": { \"age\": { \"order\": \"desc\" } }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 查询返回指定的字段(这样操作有点类似于SQL SELECT FROM field lis)
 */
 @Test
 public void findByLimitField() throws Exception{
        String DSL = "{\n" +
                " \"query\": { \"match_all\": {} },\n" +
                " \"_source\": [\"name\", \"age\"]\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }


    /**
 * 布尔值(bool)查询(返回 匹配name=张1 & age=21)
 */
 @Test
 public void findByMustBool() throws Exception{
        String DSL = "{\n" +
                " \"query\": {\n" +
                " \"bool\": {\n" +
                " \"must\": [\n" +
                " { \"match\": { \"name\": \"张1\" } },\n" +
                " { \"match\": { \"age\": \"21\" } }\n" +
                " ]\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 布尔值(bool)查询(返回 匹配name=张1 || age=21)
 */
 @Test
 public void findByOrBool() throws Exception{
        String DSL = "{\n" +
                " \"query\": {\n" +
                " \"bool\": {\n" +
                " \"should\": [\n" +
                " { \"match\": { \"name\": \"张1\" } },\n" +
                " { \"match\": { \"age\": \"21\" } }\n" +
                " ]\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }
    /**
 * 布尔值(bool)查询(返回 不匹配name=张1 & age=21)
 */
 @Test
 public void findByMachNotBool() throws Exception{
        String DSL = "{\n" +
                " \"query\": {\n" +
                " \"bool\": {\n" +
                " \"must_not\": [\n" +
                " { \"match\": { \"name\": \"张1\" } },\n" +
                " { \"match\": { \"age\": \"21\" } }\n" +
                " ]\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 布尔值(bool)查询(返回 name=张1 & age!=21)
 */
 @Test
 public void findByMachAndNotBool() throws Exception{
        String DSL = "{\n" +
                " \"query\": {\n" +
                " \"bool\": {\n" +
                " \"must\": [\n" +
                " { \"match\": { \"name\": \"张1\" } }\n" +
                " ],\n" +
                " \"must_not\": [\n" +
                " { \"match\": { \"age\": \"21\" } }\n" +
                " ]\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }


    /**
 * 范围查询(age在25到28岁之间)
 */
 @Test
 public void findByRang() throws Exception{
        String DSL = "{\n" +
                " \"query\": {\n" +
                " \"range\" : {\n" +
                " \"age\" : {\n" +
                " \"gte\" : 25,\n" +
                " \"lte\" : 28,\n" +
                " \"boost\" : 2.0\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "GET",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 分组查询(按年龄分组查询,降序统计top 10)
 *类似 SELECT age, COUNT(*) FROM user GROUP BY age ORDER BY COUNT(*) DESC
 */
 @Test
 public void findByGroup() throws Exception{
        String DSL = "{\n" +
                " \"size\": 0,\n" +
                " \"aggs\": {\n" +
                " \"group_by_age\": {\n" +
                " \"terms\": {\n" +
                " \"field\": \"age\"\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 分组查询(按年龄分组查询,查询组里其他字段的平均值)
 *类似 SELECT age, avg(age) FROM user GROUP BY age ORDER BY COUNT(*) DESC
 */
 @Test
 public void findByGroupAndAvag() throws Exception{
        String DSL = "{\n" +
                " \"size\": 0,\n" +
                " \"aggs\": {\n" +
                " \"group_by_age\": {\n" +
                " \"terms\": {\n" +
                " \"field\": \"age\"\n" +
                " },\n" +
                " \"aggs\": {\n" +
                " \"average_age\": {\n" +
                " \"avg\": {\n" +
                " \"field\": \"age\"\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 分组查询(按年龄分组查询,并且降序排序)
 *类似 SELECT age, avg(age) FROM user GROUP BY age ORDER BY avg(age) DESC
 */
 @Test
 public void findByGroupAndOrderBy() throws Exception{
        String DSL = "{\n" +
                " \"size\": 0,\n" +
                " \"aggs\": {\n" +
                " \"group_by_age\": {\n" +
                " \"terms\": {\n" +
                " \"field\": \"age\",\n" +
                " \"order\": {\n" +
                " \"average_age\": \"desc\"\n" +
                " }\n" +
                " },\n" +
                " \"aggs\": {\n" +
                " \"average_age\": {\n" +
                " \"avg\": {\n" +
                " \"field\": \"age\"\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_search",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }


    /**
 * 删除操作
 */
 @Test
 public void testDelete() throws Exception{
        Response response = restClient.performRequest(
                "DELETE",
                "userindex/user/100",
                Collections.emptyMap());
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 根据条件删除(使用_delete_by_query,POST请求)
 */
 @Test
 public void testDeleteByQuery()throws Exception{
        String DSL ="{\n" +
                " \"query\": {\n" +
                " \"match\" : {\n" +
                " \"name\" : \"张1\"\n" +
                " }\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/_delete_by_query",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }


    /**
 * 跟新操作(1. 从旧文档中检索JSON
 2. 修改它
 3. 删除旧文档
 4. 索引新文档)
 */
 @Test
 public void testUpdate() throws Exception{
        User user = new User();
        user.setId(100L);
        user.setAge(20);
        user.setName("张三修改");
        user.setSex(1);

        HttpEntity entity = new NStringEntity(gson.toJson(user), ContentType.APPLICATION_JSON);

        Response indexResponse = restClient.performRequest(
                "PUT",
                "userindex/user/100",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(indexResponse.getEntity()));
    }


    /**
 * 局部跟新字段(动态添加字段,添加tags和views字段)
 */
 @Test
 public void testUpdateField() throws Exception{
        String DSL ="{\n" +
                " \"doc\" : {\n" +
                " \"tags\" : [ \"testing\" ],\n" +
                " \"views\": 0\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/100/_update",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 使用脚本部分跟新字段(将views字段数量加1)
 */
 @Test
 public void testUpdateFieldByScript() throws Exception{
        String DSL ="{\n" +
                " \"script\" : \"ctx._source.views+=1\"\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/100/_update",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }

    /**
 * 将search 标签追加到 tags 数组中
 */
 @Test
 public void testUpdateFieldAddByScript() throws Exception{
        String DSL = "{\n" +
                " \"script\" : \"ctx._source.tags+=new_tag\",\n" +
                " \"params\" : {\n" +
                " \"new_tag\" : \"search\"\n" +
                " }\n" +
                "}";
        HttpEntity entity = new NStringEntity(DSL, ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
                "POST",
                "userindex/user/100/_update",
                Collections.emptyMap(),
                entity);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }


    @After
 public void closeRestClient() throws Exception{
        restClient.close();
    }


}

你可能感兴趣的:(Elasticsearch)