我的DEMO项目下载:https://gitee.com/zhuhongliang/soringboot_elastic_search_732.git

Service:

/**
 * 添加文档
 * @param obj
 */
public String createDoc(Object obj){
    /**
     * 设置索引,必须是小写,所以使用toLowerCase()方法进行转换
     */
    IndexRequest request = new IndexRequest(obj.getClass().getSimpleName().toLowerCase());
    /**
     * 设置文档id。如果不设置,系统会自动生成
     */
    //request.id("xxxx");
    request.source(JSONObject.toJSONString(obj), XContentType.JSON);
    try {
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        log.info(JSONObject.toJSONString(response));
        if(DocWriteResponse.Result.CREATED == response.getResult()){
            return response.getId();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}

/**
 * 批量处理文档
 * @param list 需要处理的文档列表
 */
public void createMultiDoc(List<Object> list){
    BulkRequest request = new BulkRequest();
    /**
     * 遍历
     * IndexRequest不设置id,让系统自己添加
     * DeleteRequest 批量删除
     * UpdateRequest 批量更新
     */
    list.forEach((obj)->{
        request.add(new IndexRequest(obj.getClass().getSimpleName().toLowerCase())
                .source(JSONObject.toJSONString(obj), XContentType.JSON));
    });
    try {
        BulkResponse bulkResponse = client.bulk(request,RequestOptions.DEFAULT);
        log.info(JSONObject.toJSONString(bulkResponse));
        bulkResponse.forEach((BulkItemResponse bulkItemResponse)->{
            DocWriteResponse itemResponse = bulkItemResponse.getResponse();
            switch (bulkItemResponse.getOpType()) {
                case INDEX:
                case CREATE:
                    IndexResponse indexResponse = (IndexResponse) itemResponse;
                    log.info(JSONObject.toJSONString(indexResponse));
                    if(DocWriteResponse.Result.CREATED == indexResponse.getResult()){
                        log.info("添加成功");
                    }
                    break;
                case UPDATE:
                    UpdateResponse updateResponse = (UpdateResponse) itemResponse;
                    break;
                case DELETE:
                    DeleteResponse deleteResponse = (DeleteResponse) itemResponse;
                    break;
                default:break;
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

测试类:

/**
     * 测试添加文档
     */
    @Test
    public void createDoc(){
        Article article = new Article();
        article.setTitle("水调歌头·明月几时有");
        article.setContent("丙辰中秋,欢饮达旦,大醉,作此篇,兼怀子由。\n" +
                "\n" +
                "明月几时有?把酒问青天。不知天上宫阙,今夕是何年。我欲乘风归去,又恐琼楼玉宇,高处不胜寒。起舞弄清影,何似在人间?(何似 一作:何时;又恐 一作:惟 / 唯恐)\n" +
                "转朱阁,低绮户,照无眠。不应有恨,何事长向别时圆?人有悲欢离合,月有阴晴圆缺,此事古难全。但愿人长久,千里共婵娟。(长向 一作:偏向)");
        article.setCreate_time(new Date());
        String result = commodityServiceImpl.createDoc(article);
        log.info("添加文档返回的id:{}",result);
    }
/**
 * 测试批量添加文档
 */
@Test
public void createMultiDoc(){


    Article article1 = new Article();
    article1.setTitle("声声慢·寻寻觅觅");
    article1.setContent("寻寻觅觅,冷冷清清,凄凄惨惨戚戚。乍暖还寒时候,最难将息。三杯两盏淡酒,怎敌他、晚来风急?雁过也,正伤心,却是旧时相识。\n" +
            "满地黄花堆积,憔悴损,如今有谁堪摘?守着窗儿,独自怎生得黑?梧桐更兼细雨,到黄昏、点点滴滴。这次第,怎一个愁字了得!(守着窗儿 一作:守著窗儿)测试春晚");
    article1.setCreate_time(new Date());

    Article article2 = new Article();
    article2.setTitle("卜算子·咏梅");
    article2.setContent("驿外断桥边,寂寞开无主。已是黄昏独自愁,更著风和雨。(著 同:着) \n" +
            "无意苦争春,一任群芳妒。零落成泥碾作尘,只有香如故。");
    article2.setCreate_time(new Date());

    Article article3 = new Article();
    article3.setTitle("武陵春·春晚");
    article3.setContent("风住尘香花已尽,日晚倦梳头。物是人非事事休,欲语泪先流。\n" +
            "闻说双溪春尚好,也拟泛轻舟。只恐双溪舴艋舟,载不动许多愁。测试寻寻觅觅咏梅.测试咏梅");
    article3.setCreate_time(new Date());

    List<Object> list = new ArrayList<>();
    list.add(article1);
    list.add(article2);
    list.add(article3);

    commodityServiceImpl.createMultiDoc(list);
}

运行测试类的批量添加之后控制台输出:

2019-09-21 00:31:08.468  INFO 230324 --- [           main] c.z.e.service.impl.ServiceImpl           : {"fragment":false,"id":"LTODT20Bk6nS0BLhTTX_","index":"article","primaryTerm":1,"result":"CREATED","seqNo":0,"shardId":{"fragment":true,"id":-1,"index":{"fragment":false,"name":"article","uUID":"_na_"},"indexName":"article"},"shardInfo":{"failed":0,"failures":[],"fragment":false,"successful":1,"total":1},"type":"_doc","version":1}
2019-09-21 00:31:08.468  INFO 230324 --- [           main] c.z.e.service.impl.ServiceImpl           : 添加成功
2019-09-21 00:31:08.469  INFO 230324 --- [           main] c.z.e.service.impl.ServiceImpl           : {"fragment":false,"id":"LjODT20Bk6nS0BLhTTX_","index":"article","primaryTerm":1,"result":"CREATED","seqNo":1,"shardId":{"fragment":true,"id":-1,"index":{"fragment":false,"name":"article","uUID":"_na_"},"indexName":"article"},"shardInfo":{"failed":0,"failures":[],"fragment":false,"successful":1,"total":1},"type":"_doc","version":1}
2019-09-21 00:31:08.469  INFO 230324 --- [           main] c.z.e.service.impl.ServiceImpl           : 添加成功
2019-09-21 00:31:08.469  INFO 230324 --- [           main] c.z.e.service.impl.ServiceImpl           : {"fragment":false,"id":"LzODT20Bk6nS0BLhTTX_","index":"article","primaryTerm":1,"result":"CREATED","seqNo":2,"shardId":{"fragment":true,"id":-1,"index":{"fragment":false,"name":"article","uUID":"_na_"},"indexName":"article"},"shardInfo":{"failed":0,"failures":[],"fragment":false,"successful":1,"total":1},"type":"_doc","version":1}
2019-09-21 00:31:08.469  INFO 230324 --- [           main] c.z.e.service.impl.ServiceImpl           : 添加成功

在kibana中查看mapping,发现实体类Article的create_time也出现了

{
  "mapping": {
    "properties": {
      "content": {
        "type": "text",
        "analyzer": "ik_max_word"
      },
      "create_time": {
        "type": "long"
      },
      "title": {
        "type": "text",
        "analyzer": "ik_max_word"
      }
    }
  }
}

也可以在后台看到新创建的文档数量

在Dev Tools 页面执行GET /article/_search 查看:上面使用批量添加接口添加的文档已经出现了

 

 

 

我的DEMO项目下载:https://gitee.com/zhuhongliang/soringboot_elastic_search_732.git

发表评论