package org.jeecg.modules.elasticsearch.controller;

import cn.com.ctop.common.module.entity.DataLabels;
import cn.com.ctop.common.module.utils.ElasticsearchUtil;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * es请求
 *
 * @author zzy
 * @create: 2021-07-12
 */
@Slf4j
@RestController
@RequestMapping("/es")
public class ESController {

    @Autowired
    ElasticsearchUtil elasticsearchUtil;

    @RequestMapping("createIndex")
    public void createIndex() {
        DataLabels dataLabels = new DataLabels();
        dataLabels
                .setId("3");
        dataLabels
                .setContent("哦哦哦，测试es啦，I LOVE CHINA");
        dataLabels
                .setSize(1024);
        try {
            boolean indexIfNotExist = elasticsearchUtil.createIndexIfNotExist(DataLabels.class);
            log.info("创建成功:{}", indexIfNotExist);
        } catch (Exception e) {
            log.info("创建错误：{}", e.toString());
        }
    }

    @RequestMapping("addData")
    public void addData() {
        DataLabels dataLabels = new DataLabels();
        dataLabels
                .setId(UUID.randomUUID().toString());
        dataLabels
                .setContent("哦哦哦，测试es啦，I LOVE CHINA");
        dataLabels
                .setSize(1024);
        try {
            IndexResponse indexResponse = elasticsearchUtil.index(dataLabels);
            log.info("添加数据成功:{}", indexResponse.toString());
        } catch (Exception e) {
            log.info("添加数据错误：{}", e.toString());
            e.printStackTrace();
        }
    }

    @RequestMapping("searchData")
    public void searchData() {
        SearchSourceBuilder SearchSourceBuilder = new SearchSourceBuilder();
        WildcardQueryBuilder wildcardQueryBuilder = QueryBuilders.wildcardQuery("content", "*LOVE*");

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(wildcardQueryBuilder);
        SearchSourceBuilder.query(boolQueryBuilder);
        try {
            PageInfo<DataLabels> indexResponse = elasticsearchUtil.search(SearchSourceBuilder, 1, 10, DataLabels.class);
            log.info("查询数据成功:{}", indexResponse.toString());
        } catch (Exception e) {
            log.info("查询数据错误：{}", e.toString());
            e.printStackTrace();
        }
    }
}
