ElasticSearch bulk 批量同步数据

公司项目要求使用 ElasticSearch ,本篇介绍一下开发环境的数据导入,并没有使用 ES 的 java api,思路如下:

  • java 生成 .json 文件
  • curl 向 ElasticSearch 服务器发送 _bulk 请求,完成批量同步
须知:
create  当文档不存在时创建之
index   创建新文档或替换已有文档
update  局部更新文档
delete  删除一个文档

json 格式如下,每一行 json 结束必须换行

POST /_bulk
{"index":{"_index":"station_index","_type":"station","_id":570}}
{"name":"燕南变电站","id":570,"table":"station"}
{"index":{"_index":"station_index","_type":"station","_id":604}}
{"name":"王石变电站","id":604,"table":"station"}
{"index":{"_index":"station_index","_type":"station","_id":605}}
{"name":"鞍山变电站","id":605,"table":"station"}

官方建议 bulk 批次最好不要超过15MB,由于我并没有那么庞大的数据量,所以在写入的时候并没有分文件。

实践:

1)json 文件生成(PS:基础很烂,IO流不太熟,凑合看吧)

/**
 * ElasticSearch 常量
 * ACTION_* : bulk api json key
 * ES_* : ElasticSearch 中常见属性
 * 
 * @author Taven
 *
 */
public class ESConstant {
    
    /**
     * bulk api json key 当文档不存在时创建之
     */
    public static final String ACTION_CREATE = "create";
    
    /**
     * bulk api json key 创建新文档或替换已有文档
     */
    public static final String ACTION_INDEX = "index";
    
    /**
     * bulk api json key 局部更新文档
     */
    public static final String ACTION_UPDATE = "update";
    
    /**
     * bulk api json key 删除一个文档
     */
    public static final String ACTION_DELETE = "delete";
    
    /**
     * ES中的索引
     */
    public static final String ES_INDEX = "_index";
    
    /**
     * ES中的类型
     */
    public static final String ES_TYPE = "_type";
    
    /**
     * ES中的id
     */
    public static final String ES_ID = "_id";
    
}

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wansidong.communicate.beans.ESConstant;
import com.wansidong.communicate.model.Cable4ES;
import com.wansidong.communicate.model.Station4ES;
import com.wansidong.communicate.model.Transmission4ES;

/**
 * ESHelper 工具类
 * 
 * @author Taven
 *
 */
public class ESHelper {

    private static final Logger logger = LoggerFactory.getLogger(ESHelper.class);
    
    /**
     * 分隔符
     */
    private static String separator = System.getProperty("file.separator");

    /**
     * 创建 es_data.json 文件并写入数据
     * 
     * @param staionList
     * @param cableList
     * @param transList
     */
    public static void writeESJsonData(List<Station4ES> staionList) {
        String tomcatPath = System.getProperty("catalina.home");
        String directoryPath = tomcatPath + separator + "data";// 目录路径
        String filePath = tomcatPath + separator + "data" + separator + "es_data.json";// 文件路径
        File directory = new File(directoryPath);// 目录File
        File file = new File(filePath);// 文件File
        if (!directory.exists())
            directory.mkdirs();// 创建目录

        try {
            if (!file.exists())
                file.createNewFile();// 创建文件
            FileWriter writer = new FileWriter(filePath);
            writer.write(parseStation4ES(staionList));
            writer.flush();
            writer.close();
            logger.info("json文件已生成! path:" + filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        
    }

    /**
     * 将站点数据转换为 json 字符串
     * 
     * @param staionList
     * @return
     * @throws JsonProcessingException
     */
    private static String parseStation4ES(List<Station4ES> staionList) throws JsonProcessingException {
        Map<String, Object> actionMap = new HashMap<String, Object>();// bulk action
        Map<String, Object> metadataMap = new HashMap<String, Object>();// bulk metadata
        Map<String, Object> bodyMap = new HashMap<String, Object>();// bulk request body
        ObjectMapper mapper = new ObjectMapper();
        StringBuffer stringBuffer = new StringBuffer();

        for (Station4ES station4es : staionList) {
            actionMap.clear();
            metadataMap.clear();
            bodyMap.clear();

            // 封装 bulk 所需的数据类型
            // { action: { metadata }}\n
            // { request body }\n
            metadataMap.put(ESConstant.ES_INDEX, station4es.getTable() + "_index");
            metadataMap.put(ESConstant.ES_TYPE, station4es.getTable());
            metadataMap.put(ESConstant.ES_ID, station4es.getId());
            actionMap.put(ESConstant.ACTION_INDEX, metadataMap);// action
            bodyMap.put("id", station4es.getId());
            bodyMap.put("name", station4es.getName());
            bodyMap.put("table", station4es.getTable());

            stringBuffer.append(mapper.writeValueAsString(actionMap));
            stringBuffer.append(System.getProperty("line.separator"));
            stringBuffer.append(mapper.writeValueAsString(bodyMap));
            stringBuffer.append(System.getProperty("line.separator"));
        }
        return stringBuffer.toString();
    }

}

2)使用 curl 向 ES 服务器发送请求
windows 如何安装 curl 链接在下面,linux 的同学先自行百度。

# cmd 进入 curl\I386 执行以下命令 ,@后面是你的文件所在位置
curl -l -H "Content-Type:application/json" -H "Accept:applic
ation/json" -XPOST localhost:9200/_bulk?pretty --data-binary @F:\apache-tomcat-8.
0.44\data\es_data.json

数据同步成功

学习:
ElasticSearch 权威指南(中文版) https://es.xiaoleilu.com/
环境搭建:
Windows 下安装 ElasticSearch & ElasticSearch head https://www.jianshu.com/p/4467cfe4e651
Windows 环境下 curl 安装和使用 https://blog.csdn.net/qq_21126979/article/details/78690960

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 简介 Elasticsearch是一个高可扩展的开源全文搜索和分析引擎,它允许存储、搜索和分析大量的数据,并且这个...
    零度沸腾_yjz阅读 10,831评论 0 8
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,725评论 19 139
  • 在日常工作当中,经常遇到因为分配不合理出现两个人都是老大,谁都不让谁。 就像手表定律,如果你带了两...
    城市格调刘姣阅读 2,593评论 0 0
  • 概念: 45°精进曲线。为什么是45°?因为进步的坡道要足够陡峭,才能快速匹配用户需求的变化,同时也是给竞争对手的...
    微光芒阅读 2,415评论 0 0
  • 亲爱的朋友, 祝好!昨日颓废了一天,看了大半天的狼人杀,恨不得自己撸袖子上,但是想玩游戏之际,却又感到莫名的空虚...
    居无所处阅读 1,365评论 0 0