package com.zjty.dev.device.es;

import com.zjty.dev.device.es.subject.entity.CollectionRs;
import com.zjty.dev.device.es.subject.entity.EsSource;
import com.zjty.dev.device.es.subject.service.EsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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

/**
 * @author LJJ cnljj1995@gmail.com
 * on 1/23/21
 */
@SpringBootTest
@Slf4j
public class Test {

    @Autowired
    private EsUtil esUtil;


    /**
     * 创建索引测试
     * @throws Exception e
     */
    @org.junit.jupiter.api.Test
    public void createIndexTest() throws Exception {

        // 需要分词的字段
        Map<String, Object> text = new HashMap<>();
        text.put("type", "text");
        text.put("analyzer", "ik_max_word");
        text.put("search_analyzer", "ik_max_word");

        // 不需要分词的字段
        Map<String, Object> keyword = new HashMap<>();
        keyword.put("type", "keyword");


        Map<String, Object> properties = new HashMap<>();
        properties.put("title", text);
        properties.put("updateTime", keyword);
        properties.put("content", text);

        Map<String, Object> mapping = new HashMap<>();
        mapping.put("properties", properties);

        esUtil.createIndex("dev_test", mapping);
    }


    /**
     * 模拟添加数据测试
     * @throws Exception e
     */
    @org.junit.jupiter.api.Test
    public void addData() throws Exception {

        List<EsSource> list = new ArrayList<>();

        for (int i = 0; i < 100; i++) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("content", "中华人民共和国成立20周年，阿斯顿马丁是辆豪车"+i);
            map.put("updateTime", 123333);
            map.put("title", "这是一个正常的标题");

            list.add(EsSource
                    .builder()
                    .id(i + "")
                    .jsonMap(map)
                    .build());
        }


        esUtil.bulkAdd("dev_test", list);
    }

    /**
     *  搜索测试
     */
    @org.junit.jupiter.api.Test
    public void searchTest() {
        CollectionRs search = esUtil.search("dev_test", "中华", 0, 50);
        log.info("数量:{}，内容:{}",search.getIds().size(), search.toString() );
    }

    /**
     * 删除测试
     */
    @org.junit.jupiter.api.Test
    public void delByBulkTest() {
        List<String> ids = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            ids.add(i+"");
        }
        esUtil.bulkDel("dev_test",ids);

    }

}
