Java 操作 ElasticSearch


在这里插入图片描述

  使用 kibana。
  当创建索引并填充数据后,可以在 Discover 里查看。
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

  代码结构。
在这里插入图片描述


// pom.xml

<dependencies>
        <!--        1. elasticsearch-->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.5.4</version>
        </dependency>

        <!--        2. elasticsearch的高级API-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.5.4</version>
        </dependency>

        <!--        3. junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!--        4. lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
        <!-- 5json -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>


// man.java

@Data
@AllArgsConstructor
@NoArgsConstructor

public class Man implements Serializable {

    private Integer id;
    private String name;
    private Integer age;
    private String sex;

}


// ESUtils.java

public class ESUtils {


    public static RestHighLevelClient getClient() {
        HttpHost host = new HttpHost("172.20.10.2", 9200);
        RestClientBuilder builder = RestClient.builder(host);
        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;
    }

}

  基本用法。


public class TestES {


    @Test
    public void t1() throws IOException {
        // 创建索引 index
        CreateIndexRequest request = new CreateIndexRequest("person");

        // setting
        Settings.Builder setting = Settings.builder()
                .put("number_of_shards", 5)
                .put("number_of_replicas", 1);

        // 属性
        XContentBuilder mapping = JsonXContent.contentBuilder();
        mapping
                .startObject()
                    .startObject("properties")
                        .startObject("name")
                            .field("type", "text")
                        .endObject()
                        .startObject("age")
                            .field("type", "integer")
                        .endObject()
                        .startObject("sex")
                             .field("type", "text")
                        .endObject()
                    .endObject()
                .endObject();
        // 文档 type
        request.settings(setting).mapping("man", mapping);

        // 发送请求
        CreateIndexResponse createIndexResponse = ESUtils.getClient().indices().create(request, RequestOptions.DEFAULT);

        System.out.println("创建索引结果:" + createIndexResponse.isAcknowledged());

    }


    @Test
    public void t2() throws IOException {

        // 查询索引是否存在
        GetIndexRequest request = new GetIndexRequest();
        request.indices("person");

        boolean exists = ESUtils.getClient().indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    @Test
    public void t3() throws IOException {

        DeleteIndexRequest request = new DeleteIndexRequest("person");
        AcknowledgedResponse delete = ESUtils.getClient().indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());

    }

    @Test
    public void t4() throws IOException {

        // 添加数据
        Man man = new Man(1, "zs", 16, "男");

        // Jackson 序列化
        ObjectMapper om = new ObjectMapper();
        String s = om.writeValueAsString(man);

//        Man man1 = om.readValue(s, Man.class);

        // 指定 id
        IndexRequest request = new IndexRequest("person", "man", man.getId().toString());
        request.source(s, XContentType.JSON);

        IndexResponse indexResponse = ESUtils.getClient().index(request, RequestOptions.DEFAULT);
        System.out.println(indexResponse.getResult());

    }

    @Test
    public void t5() throws IOException {

        // 修改数据
        Map<String, String> map = new HashMap<>();
        map.put("name", "ls");

        UpdateRequest request = new UpdateRequest("person", "man", "1");
        request.doc(map);

        UpdateResponse update = ESUtils.getClient().update(request, RequestOptions.DEFAULT);
        System.out.println(update.getResult());
    }

    @Test
    public void t6() throws IOException {
        // 删除数据
        DeleteRequest request = new DeleteRequest("person", "man", "1");
        DeleteResponse deleteResponse = ESUtils.getClient().delete(request, RequestOptions.DEFAULT);
        System.out.println(deleteResponse.getResult());
    }

    @Test
    public void t7() throws IOException {

        // 批量新增
        Man man1 = new Man(1, "zs1", 14, "男");
        Man man2 = new Man(1, "zs2", 15, "男");
        Man man3 = new Man(1, "zs3", 16, "男");

        ObjectMapper om = new ObjectMapper();
        String string1 = om.writeValueAsString(man1);
        String string2 = om.writeValueAsString(man2);
        String string3 = om.writeValueAsString(man3);

        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest("person", "man","1").source(string1, XContentType.JSON));
        request.add(new IndexRequest("person", "man","2").source(string2, XContentType.JSON));
        request.add(new IndexRequest("person", "man","3").source(string3, XContentType.JSON));

        BulkResponse bulk = ESUtils.getClient().bulk(request, RequestOptions.DEFAULT);

        // 结果
        for (BulkItemResponse item : bulk.getItems()) {
            System.out.println(item.getResponse().getResult());
        }

    }

    @Test
    public void t8() throws IOException {
        // 批量删除
        BulkRequest request = new BulkRequest();
        request.add(new DeleteRequest("person", "man", "1"));
        request.add(new DeleteRequest("person", "man", "2"));

        BulkResponse bulk = ESUtils.getClient().bulk(request, RequestOptions.DEFAULT);

        // 结果
        for (BulkItemResponse item : bulk.getItems()) {
            System.out.println(item.getResponse().getResult());
        }

    }

}

  ES 主要用来做查询。

  先创建索引,填充测试数据。


// SmsLogs.java

@Data
@NoArgsConstructor
@AllArgsConstructor
public class SmsLogs {

    private String id;// 唯一ID 1

    private Date createDate;// 创建时间

    private Date sendDate; // 发送时间

    private String longCode;// 发送的长号码

    private String mobile;// 下发手机号

    private String corpName;// 发送公司名称

    private String smsContent; // 下发短信内容

    private Integer state; // 短信下发状态 0 成功 1 失败

    private Integer operatorId; // '运营商编号 1 移动 2 联通 3 电信

    private String province;// 省份

    private String ipAddr; //下发服务器IP地址

    private Integer replyTotal; //短信状态报告返回时长(秒)

    private Integer fee;  // 费用

}



public class TestData {
    ObjectMapper mapper = new ObjectMapper();
    RestHighLevelClient client = ESUtils.getClient();
    String index = "sms-logs-index";
    String type = "sms-logs-type";
	
	@Test
    public void createSmsLogsIndex() throws IOException {

        //1. settings
        Settings.Builder settings = Settings.builder()
                .put("number_of_shards", 3)
                .put("number_of_replicas", 1);

        //2. mapping.
        XContentBuilder mapping = JsonXContent.contentBuilder()
                .startObject()
					.startObject("properties")
						.startObject("createDate")
							.field("type", "date")
						.endObject()
						.startObject("sendDate")
							.field("type", "date")
						.endObject()
						.startObject("longCode")
							.field("type", "keyword")
						.endObject()
						.startObject("mobile")
							.field("type", "keyword")
						.endObject()
						.startObject("corpName")
							.field("type", "keyword")
						.endObject()
						.startObject("smsContent")
							.field("type", "text")

						.endObject()
						.startObject("state")
							.field("type", "integer")
						.endObject()
						.startObject("operatorId")
							.field("type", "integer")
						.endObject()
						.startObject("province")
							.field("type", "keyword")
						.endObject()
						.startObject("ipAddr")
							.field("type", "ip")
						.endObject()
						.startObject("replyTotal")
							.field("type", "integer")
						.endObject()
						.startObject("fee")
							.field("type", "long")
						.endObject()
					.endObject()
                .endObject();

        //3. 添加索引.
        CreateIndexRequest request = new CreateIndexRequest(index);
        request.settings(settings);
        request.mapping(type,mapping);
        client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println("OK!!");
    }
	
    @Test
    public void addTestData() throws IOException {
        BulkRequest request = new BulkRequest();

        SmsLogs smsLogs = new SmsLogs();
        smsLogs.setMobile("13800000000");
        smsLogs.setCorpName("途虎养车");
        smsLogs.setCreateDate(new Date());
        smsLogs.setSendDate(new Date());
        smsLogs.setIpAddr("10.126.2.9");
        smsLogs.setLongCode("10690000988");
        smsLogs.setReplyTotal(10);
        smsLogs.setState(0);
        smsLogs.setSmsContent("【途虎养车】亲爱的张三先生/女士,您在途虎购买的货品(单号TH123456)已 到指定安装店多日," + "现需与您确认订单的安装情况,请点击链接按实际情况选择(此链接有效期为72H)。您也可以登录途 虎APP进入" + "“我的-待安装订单”进行预约安装。若您在服务过程中有任何疑问,请致电400-111-8868向途虎咨 询。");
        smsLogs.setProvince("北京");
        smsLogs.setOperatorId(1);
        smsLogs.setFee(3);
        request.add(new IndexRequest(index, type, "21").source(mapper.writeValueAsString(smsLogs), XContentType.JSON));

        smsLogs.setMobile("13700000001");
        smsLogs.setProvince("上海");
        smsLogs.setSmsContent("【途虎养车】亲爱的刘红先生/女士,您在途虎购买的货品(单号TH1234526)已 到指定安装店多日," + "现需与您确认订单的安装情况,请点击链接按实际情况选择(此链接有效期为72H)。您也可以登录途 虎APP进入" + "“我的-待安装订单”进行预约安装。若您在服务过程中有任何疑问,请致电400-111-8868向途虎咨 询。");
        request.add(new IndexRequest(index, type, "22").source(mapper.writeValueAsString(smsLogs), XContentType.JSON));


        // -------------------------------------------------------------------------------------------------------------------

        SmsLogs smsLogs1 = new SmsLogs();
        smsLogs1.setMobile("13100000000");
        smsLogs1.setCorpName("盒马鲜生");
        smsLogs1.setCreateDate(new Date());
        smsLogs1.setSendDate(new Date());
        smsLogs1.setIpAddr("10.126.2.9");
        smsLogs1.setLongCode("10660000988");
        smsLogs1.setReplyTotal(15);
        smsLogs1.setState(0);
        smsLogs1.setSmsContent("【盒马】您尾号12345678的订单已开始配送,请在您指定的时间收货不要走开 哦~配送员:" + "刘三,电话:13800000000");
        smsLogs1.setProvince("北京");
        smsLogs1.setOperatorId(2);
        smsLogs1.setFee(5);
        request.add(new IndexRequest(index, type, "23").source(mapper.writeValueAsString(smsLogs1), XContentType.JSON));

        smsLogs1.setMobile("18600000001");
        smsLogs1.setProvince("上海");
        smsLogs1.setSmsContent("【盒马】您尾号7775678的订单已开始配送,请在您指定的时间收货不要走开 哦~配送员:" + "王五,电话:13800000001");
        request.add(new IndexRequest(index, type, "24").source(mapper.writeValueAsString(smsLogs1), XContentType.JSON));

        // -------------------------------------------------------------------------------------------------------------------

        SmsLogs smsLogs2 = new SmsLogs();
        smsLogs2.setMobile("15300000000");
        smsLogs2.setCorpName("滴滴打车");
        smsLogs2.setCreateDate(new Date());
        smsLogs2.setSendDate(new Date());
        smsLogs2.setIpAddr("10.126.2.8");
        smsLogs2.setLongCode("10660000988");
        smsLogs2.setReplyTotal(50);
        smsLogs2.setState(1);
        smsLogs2.setSmsContent("【滴滴单车平台】专属限时福利!青桔/小蓝月卡立享5折,特惠畅骑30天。" + "戳 https://xxxxxx退订TD");
        smsLogs2.setProvince("上海");
        smsLogs2.setOperatorId(3);
        smsLogs2.setFee(7);
        request.add(new IndexRequest(index, type, "25").source(mapper.writeValueAsString(smsLogs2), XContentType.JSON));

        smsLogs2.setMobile("18000000001");
        smsLogs2.setProvince("武汉");
        smsLogs2.setSmsContent("【滴滴单车平台】专属限时福利!青桔/小蓝月卡立享5折,特惠畅骑30天。" + "戳 https://xxxxxx退订TD");
        request.add(new IndexRequest(index, type, "26").source(mapper.writeValueAsString(smsLogs2), XContentType.JSON));


        // -------------------------------------------------------------------------------------------------------------------

        SmsLogs smsLogs3 = new SmsLogs();
        smsLogs3.setMobile("13900000000");
        smsLogs3.setCorpName("招商银行");
        smsLogs3.setCreateDate(new Date());
        smsLogs3.setSendDate(new Date());
        smsLogs3.setIpAddr("10.126.2.8");
        smsLogs3.setLongCode("10690000988");
        smsLogs3.setReplyTotal(50);
        smsLogs3.setState(0);
        smsLogs3.setSmsContent("【招商银行】尊贵的李四先生,恭喜您获得华为P30 Pro抽奖资格,还可领100 元打" + "车红包,仅限1天");
        smsLogs3.setProvince("上海");
        smsLogs3.setOperatorId(1);
        smsLogs3.setFee(8);
        request.add(new IndexRequest(index, type, "27").source(mapper.writeValueAsString(smsLogs3), XContentType.JSON));

        smsLogs3.setMobile("13990000001");
        smsLogs3.setProvince("武汉");
        smsLogs3.setSmsContent("【招商银行】尊贵的李四先生,恭喜您获得华为P30 Pro抽奖资格,还可领100 元打" + "车红包,仅限1天");
        request.add(new IndexRequest(index, type, "28").source(mapper.writeValueAsString(smsLogs3), XContentType.JSON));

        // -------------------------------------------------------------------------------------------------------------------

        SmsLogs smsLogs4 = new SmsLogs();
        smsLogs4.setMobile("13700000000");
        smsLogs4.setCorpName("中国平安保险有限公司");
        smsLogs4.setCreateDate(new Date());
        smsLogs4.setSendDate(new Date());
        smsLogs4.setIpAddr("10.126.2.8");
        smsLogs4.setLongCode("10690000998");
        smsLogs4.setReplyTotal(18);
        smsLogs4.setState(0);
        smsLogs4.setSmsContent("【中国平安】奋斗的时代,更需要健康的身体。中国平安为您提供多重健康保 障,在奋斗之路上为您保驾护航。退订请回复TD");
        smsLogs4.setProvince("武汉");
        smsLogs4.setOperatorId(1);
        smsLogs4.setFee(5);
        request.add(new IndexRequest(index, type, "29").source(mapper.writeValueAsString(smsLogs4), XContentType.JSON));

        smsLogs4.setMobile("13990000002");
        smsLogs4.setProvince("武汉");
        smsLogs4.setSmsContent("【招商银行】尊贵的王五先生,恭喜您获得iphone 56抽奖资格,还可领5 元打" + "车红包,仅限100天");
        request.add(new IndexRequest(index, type, "30").source(mapper.writeValueAsString(smsLogs4), XContentType.JSON));

        // -------------------------------------------------------------------------------------------------------------------


        SmsLogs smsLogs5 = new SmsLogs();
        smsLogs5.setMobile("13600000000");
        smsLogs5.setCorpName("中国移动");
        smsLogs5.setCreateDate(new Date());
        smsLogs5.setSendDate(new Date());
        smsLogs5.setIpAddr("10.126.2.8");
        smsLogs5.setLongCode("10650000998");
        smsLogs5.setReplyTotal(60);
        smsLogs5.setState(0);
        smsLogs5.setSmsContent("【北京移动】尊敬的客户137****0000,5月话费账单已送达您的139邮箱," + "点击查看账单详情 http://y.10086.cn/; " + " 回Q关闭通知,关注“中国移动139邮箱”微信随时查账单【中国移动 139邮箱】");
        smsLogs5.setProvince("武汉");
        smsLogs5.setOperatorId(1);
        smsLogs5.setFee(4);
        request.add(new IndexRequest(index, type, "31").source(mapper.writeValueAsString(smsLogs5), XContentType.JSON));

        smsLogs5.setMobile("13990001234");
        smsLogs5.setProvince("山西");
        smsLogs5.setSmsContent("【北京移动】尊敬的客户137****1234,8月话费账单已送达您的126邮箱,\" + \"点击查看账单详情 http://y.10086.cn/; \" + \" 回Q关闭通知,关注“中国移动126邮箱”微信随时查账单【中国移动 126邮箱】");
        request.add(new IndexRequest(index, type, "32").source(mapper.writeValueAsString(smsLogs5), XContentType.JSON));
        // -------------------------------------------------------------------------------------------------------------------

        client.bulk(request,RequestOptions.DEFAULT);

        System.out.println("OK!");
    }
}

  查询。


public class TestSelect {

    private String index = "sms-logs-index";
    private String type = "sms-logs-type";

    @Test
    public void t1() throws IOException {

        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 查询的起始下标, 默认 0
        builder.from(0);
        // 查询条数, 默认 10
        builder.size(2);

        // 精确查询 完全匹配
        builder.query(QueryBuilders.termQuery("province", "北"));

        SearchRequest request = new SearchRequest(index);
        request.types(type);
        request.source(builder);

        SearchResponse search = ESUtils.getClient().search(request, RequestOptions.DEFAULT);

        // 0
        System.out.println(search.getHits().getHits().length);
        // 结果
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

    @Test
    public void t2() throws IOException {

        // 精确查询 完全匹配 ,多个匹配
        builder.query(QueryBuilders.termsQuery("province", "北京", "上海"));
    }

    @Test
    public void t3() throws IOException {

        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.size(20);

        // 查询所有
        builder.query(QueryBuilders.matchAllQuery());

        SearchRequest request = new SearchRequest(index);
        request.types(type);
        request.source(builder);

        SearchResponse search = ESUtils.getClient().search(request, RequestOptions.DEFAULT);

        // 12
        System.out.println(search.getHits().getHits().length);
        // 结果
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }

    }

    @Test
    public void t4() throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();

        // 分词查询、模糊查询
        builder.query(QueryBuilders.matchQuery("smsContent","收货安装"));

        SearchRequest request = new SearchRequest(index);
        request.types(type);
        request.source(builder);

        SearchResponse search = ESUtils.getClient().search(request, RequestOptions.DEFAULT);

        System.out.println(search.getHits().getHits().length);
        // 结果
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

    @Test
    public void t5() throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();

        // 分词查询
        builder.query(QueryBuilders.matchQuery("smsContent","收货安装"));

        // 分词查询,包含 .. 也包含 ..
        builder.query(QueryBuilders.matchQuery("smsContent","中国 健康").operator(Operator.OR));

        SearchRequest request = new SearchRequest(index);
        request.types(type);
        request.source(builder);

        SearchResponse search = ESUtils.getClient().search(request, RequestOptions.DEFAULT);

        System.out.println(search.getHits().getHits().length);
        // 结果
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

    @Test
    public void t6() throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();

        // 1个关键字,在多个不同的域(属性)查找
        builder.query(QueryBuilders.multiMatchQuery("北","province", "smsContent"));

        SearchRequest request = new SearchRequest(index);
        request.types(type);
        request.source(builder);

        SearchResponse search = ESUtils.getClient().search(request, RequestOptions.DEFAULT);

        System.out.println(search.getHits().getHits().length);
        // 结果
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

    @Test
    public void t7() throws IOException {

        // 单个id查询
        GetRequest request = new GetRequest(index, type, "32");

        GetResponse res = ESUtils.getClient().get(request, RequestOptions.DEFAULT);

        System.out.println(res.getSourceAsMap());
        System.out.println(res.getId());

    }

    @Test
    public void t8() throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();

        // 查询多个id
        builder.query(QueryBuilders.idsQuery().addIds("22","32"));

        SearchRequest request = new SearchRequest(index);
        request.types(type);
        request.source(builder);

        SearchResponse search = ESUtils.getClient().search(request, RequestOptions.DEFAULT);

        System.out.println(search.getHits().getHits().length);
        // 结果
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

    @Test
    public void t9() throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();

        // 前缀查询
        builder.query(QueryBuilders.prefixQuery("province", "北"));

        SearchRequest request = new SearchRequest(index);
        request.types(type);
        request.source(builder);

        SearchResponse search = ESUtils.getClient().search(request, RequestOptions.DEFAULT);

        System.out.println(search.getHits().getHits().length);
        // 结果
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

    @Test
    public void t10() throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();

        // like, 使用*和?指定通配符和占位符
        builder.query(QueryBuilders.wildcardQuery("smsContent","*北京移动*"));

        SearchRequest request = new SearchRequest(index);
        request.types(type);
        request.source(builder);

        SearchResponse search = ESUtils.getClient().search(request, RequestOptions.DEFAULT);

        System.out.println(search.getHits().getHits().length);
        // 结果
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

    @Test
    public void t11() throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();

        // 模糊查询, pref 指定前面几个字符是不允许出现错误的
        builder.query(QueryBuilders.fuzzyQuery("corpName","中国t动").prefixLength(2));

        SearchRequest request = new SearchRequest(index);
        request.types(type);
        request.source(builder);

        SearchResponse search = ESUtils.getClient().search(request, RequestOptions.DEFAULT);

        System.out.println(search.getHits().getHits().length);
        // 结果
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

    @Test
    public void t12() throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();

        // 范围查询, e 包含
        builder.query(QueryBuilders.rangeQuery("fee").gte(5).lt(8));

        SearchRequest request = new SearchRequest(index);
        request.types(type);
        request.source(builder);

        SearchResponse search = ESUtils.getClient().search(request, RequestOptions.DEFAULT);

        System.out.println(search.getHits().getHits().length);
        // 结果
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

    @Test
    public void t13() throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();

        // 正则查询
        builder.query(QueryBuilders.regexpQuery("mobile", "139[0-9]{8}"));

        SearchRequest request = new SearchRequest(index);
        request.types(type);
        request.source(builder);

        SearchResponse search = ESUtils.getClient().search(request, RequestOptions.DEFAULT);

        System.out.println(search.getHits().getHits().length);
        // 结果
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

    @Test
    public void t14() throws IOException {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.size(2);
        // 查询所有
        builder.query(QueryBuilders.matchAllQuery());

        SearchRequest request = new SearchRequest(index);
        request.types(type);
        request.scroll(TimeValue.timeValueMinutes(1L));
        request.source(builder);

        SearchResponse search = ESUtils.getClient().search(request, RequestOptions.DEFAULT);

        System.out.println(search.getHits().getHits().length);
        System.out.println("-- --");
        //首页 结果
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }

        // 深分页 id
        String scrollId = search.getScrollId();
        while (true) {
            //  深分页,会将上页数据从查询所有中删除,以提高查下页速度,所以只能查下一页
            SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
            // 设置数据存活时间1分钟,超过1分钟,所有数据会从查询中删除,需要重新查询
            scrollRequest.scroll(TimeValue.timeValueMinutes(1L));

            SearchResponse scroll = ESUtils.getClient().scroll(scrollRequest, RequestOptions.DEFAULT);

            //分页 结果
            SearchHit[] hits = scroll.getHits().getHits();
            System.out.println("-- --");
            if (hits != null && hits.length > 0) {
                for (SearchHit hit : hits) {
                    System.out.println(hit.getSourceAsMap());
                }
            } else {
                break;
            }
        }

        ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
        clearScrollRequest.addScrollId(scrollId);

        ClearScrollResponse clearScrollResponse = ESUtils.getClient().clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
        System.out.println("-- --");
        System.out.println(clearScrollResponse.isSucceeded());
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值