【xxx-mall学习系列-基础框架使用-004】-基于ssm整合ElasticSearch7.1.0

161 阅读1分钟

在001节中的ssm整合的基础之上整合ES7.1.0,对应项目 xxx-learn-ssm-es7.1.0

1. 引入依赖

        <!-- web模块 -->
        <dependency>
            <groupId>com.xxx.basic</groupId>
            <artifactId>xxx-starter-web</artifactId>
        </dependency>

        <!--db-->
        <dependency>
            <groupId>com.xxx.basic</groupId>
            <artifactId>xxx-starter-mybatis-plus</artifactId>
        </dependency>

        <!-- elasticsearch -->
        <dependency>
            <groupId>com.xxx.basic</groupId>
            <artifactId>xxx-starter-elasticsearch</artifactId>
        </dependency>

        <dependency>
            <groupId>com.xxx.basic</groupId>
            <artifactId>xxx-starter-test</artifactId>
        </dependency>

2. 编写单元测试类

package com.xxx.learn.redis;

import com.alibaba.fastjson.JSONObject;
import com.xxx.starter.es.config.EsTemplate;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author amyzhang
 * @history 2020-09-17 新建
 * @since JDK1.8
 */
@Slf4j
public class ESTest extends BaseTestCase {

    @Autowired
    private EsTemplate esTemplate;

    @Test
    public void addOrUpdateDoc() throws Exception{

        String id = "1";
        Map<String,Object> map = new HashMap<>();
        map.put("id",1);
        map.put("name","test");
        map.put("nickName","nickName1");
        boolean result = esTemplate.addOrUpdateDoc("test-index", map, id);
        log.info("------------->{}", JSONObject.toJSONString(result));
    }

    @Test
    public void batchAdd(){
        List<Map<String,Object>> list = new ArrayList<>();
        for(int i=0;i<2000;i++){
            String id = ""+i;
            Map<String,Object> map = new HashMap<>();
            map.put("id",i);
            map.put("name","test"+i);
            map.put("nickName","nickName"+i);
            list.add(map);
        }
        boolean result = esTemplate.batchAddDoc("test-index", list);
        log.info("------------->{}", result);
    }

    @Test
    public void exists() throws Exception{
        String id = "1";
        boolean result = esTemplate.exists("test-index", id);
        log.info("------------->{}", JSONObject.toJSONString(result));
    }

    @Test
    public void deleteIndex() throws Exception{

        String id = "1";
        boolean result = esTemplate.deleteDoc("test-index", id);
        log.info("------------->{}", JSONObject.toJSONString(result));
    }
}

3. 单元测试