首页 > 其他分享 >9、Elasticsearch7.6.1 ES与HDFS相互转存数据-ES-Hadoop

9、Elasticsearch7.6.1 ES与HDFS相互转存数据-ES-Hadoop

时间:2023-07-01 10:36:04浏览次数:56  
标签:HDFS set Elasticsearch7.6 hadoop conf org apache import ES


Elasticsearch 系列文章

1、介绍lucene的功能以及建立索引、搜索单词、搜索词语和搜索句子四个示例实现2、Elasticsearch7.6.1基本介绍、2种部署方式及验证、head插件安装、分词器安装及验证
3、Elasticsearch7.6.1信息搜索示例(索引操作、数据操作-添加、删除、导入等、数据搜索及分页)
4、Elasticsearch7.6.1 Java api操作ES(CRUD、两种分页方式、高亮显示)和Elasticsearch SQL详细示例
5、Elasticsearch7.6.1 filebeat介绍及收集kafka日志到es示例
6、Elasticsearch7.6.1、logstash、kibana介绍及综合示例(ELK、grok插件)
7、Elasticsearch7.6.1收集nginx日志及监测指标示例
8、Elasticsearch7.6.1收集mysql慢查询日志及监控
9、Elasticsearch7.6.1 ES与HDFS相互转存数据-ES-Hadoop



文章目录

  • Elasticsearch 系列文章
  • 一、ES-Hadoop介绍
  • 二、ES写入HDFS
  • 1、txt文件格式写入
  • 1)、pom.xml
  • 2)、示例1:order_idx
  • 3)、示例2:tomcat_log_2023-03
  • 2、json文件格式写入
  • 三、HDFS写入ES
  • 1、txt文件写入
  • 2、json文件写入



本文简单的介绍了ES-hadoop组件功能使用,即通过ES-hadoop实现相互数据写入示例。
本文依赖es环境、hadoop环境好用。
本文分为三部分,即ES-hadoop介绍、ES数据写入hadoop和hadoop数据写入ES。

一、ES-Hadoop介绍

ES-Hadoop是Elasticsearch推出的专门用于对接Hadoop生态的工具,可以让数据在Elasticsearch和Hadoop之间双向移动,无缝衔接Elasticsearch与Hadoop服务,充分使用Elasticsearch的快速搜索及Hadoop批处理能力,实现交互式数据处理。

本文介绍如何通过ES-Hadoop实现Hadoop的Hive服务读写Elasticsearch数据。

Hadoop生态的优势是处理大规模数据集,但是其缺点也很明显,就是当用于交互式分析时,查询时延会比较长。而Elasticsearch擅长于交互式分析,对于很多查询类型,特别是对于Ad-hoc查询(即席查询),可以达到秒级。ES-Hadoop的推出提供了一种组合两者优势的可能性。使用ES-Hadoop,您只需要对代码进行很小的改动,即可快速处理存储在Elasticsearch中的数据,并且能够享受到Elasticsearch带来的加速效果。

ES-Hadoop的原理是将Elasticsearch作为MR、Spark或Hive等数据处理引擎的数据源,在计算存储分离的架构中扮演存储的角色。这和 MR、Spark或Hive的数据源并无差异,但相对于这些数据源,Elasticsearch具有更快的数据选择过滤能力。这种能力正是分析引擎最为关键的能力之一。

9、Elasticsearch7.6.1 ES与HDFS相互转存数据-ES-Hadoop_elasticsearch

二、ES写入HDFS

假设es中已经存储具体索引数据,下面仅仅是将es的数据读取并存入hdfs中。

9、Elasticsearch7.6.1 ES与HDFS相互转存数据-ES-Hadoop_hadoop_02


9、Elasticsearch7.6.1 ES与HDFS相互转存数据-ES-Hadoop_es-hadoop_03

1、txt文件格式写入

1)、pom.xml

<dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch-hadoop</artifactId>
        <version>7.6.1</version>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>transport</artifactId>
        <version>7.6.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>3.1.4</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-client</artifactId>
        <version>3.1.4</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-hdfs</artifactId>
        <version>3.1.4</version>
    </dependency>
    <dependency>
        <groupId>jdk.tools</groupId>
        <artifactId>jdk.tools</artifactId>
        <version>1.8</version>
        <scope>system</scope>
        <systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-mapreduce-client-core</artifactId>
        <version>3.1.4</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.10.1</version>
    </dependency>

2)、示例1:order_idx

将ES中的order_idx索引数据存储至hdfs中,其中hdfs是HA。hdfs中是以txt形式存储的,其中数据用逗号隔离

  • 其数据结构
key 5000,value {status=已付款, pay_money=3820.0, payway=3, userid=4405460,operation_date=2020-04-25 12:09:51, category=维修;手机;}
  • 实现
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.elasticsearch.hadoop.mr.EsInputFormat;
import org.elasticsearch.hadoop.mr.LinkedMapWritable;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ESToHdfs extends Configured implements Tool {
    private static String out = "/ES-Hadoop/test";

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        int status = ToolRunner.run(conf, new ESToHdfs(), args);
        System.exit(status);
    }

    static class ESToHdfsMapper extends Mapper<Text, LinkedMapWritable, NullWritable, Text> {
        Text outValue = new Text();

        protected void map(Text key, LinkedMapWritable value, Context context) throws IOException, InterruptedException {
//            log.info("key {} , value {}", key.toString(), value);

            Order order = new Order();
//            order.setId(Integer.parseInt(key.toString()));

            Iterator it = value.entrySet().iterator();
            order.setId(key.toString());
            String name = null;
            String data = null;
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                name = entry.getKey().toString();
                data = entry.getValue().toString();
                switch (name) {
                case "userid":
                    order.setUserid(Integer.parseInt(data));
                    break;
                case "operation_date":
                    order.setOperation_date(data);
                    break;
                case "category":
                    order.setCategory(data);
                    break;
                case "pay_money":
                    order.setPay_money(Double.parseDouble(data));
                    break;
                case "status":
                    order.setStatus(data);
                    break;
                case "payway":
                    order.setPayway(data);
                    break;
                }
            }
            //log.info("order={}", order);

            outValue.set(order.toString());
            context.write(NullWritable.get(), outValue);
        }
    }

    @Data
    static class Order {
        // key 5000 value {status=已付款, pay_money=3820.0, payway=3, userid=4405460, operation_date=2020-04-25 12:09:51, category=维修;手机;}
        private String id;
        private int userid;
        private String operation_date;
        private String category;
        private double pay_money;
        private String status;
        private String payway;

        public String toString() {
            return new StringBuilder(id).append(",").append(userid).append(",").append(operation_date).append(",").append(category).append(",").append(pay_money).append(",")
                    .append(status).append(",").append(payway).toString();
        }
    }

    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        conf.set("fs.defaultFS", "hdfs://HadoopHAcluster");
        conf.set("dfs.nameservices", "HadoopHAcluster");
        conf.set("dfs.ha.namenodes.HadoopHAcluster", "nn1,nn2");
        conf.set("dfs.namenode.rpc-address.HadoopHAcluster.nn1", "server1:8020");
        conf.set("dfs.namenode.rpc-address.HadoopHAcluster.nn2", "server2:8020");
        conf.set("dfs.client.failover.proxy.provider.HadoopHAcluster", "org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider");
        System.setProperty("HADOOP_USER_NAME", "alanchan");

        conf.setBoolean("mapred.map.tasks.speculative.execution", false);
        conf.setBoolean("mapred.reduce.tasks.speculative.execution", false);
        conf.set("es.nodes", "server1:9200,server2:9200,server3:9200");
        // ElaticSearch 索引名称
        conf.set("es.resource", "order_idx");
        // 查询索引中的所有数据,也可以加条件          
        conf.set("es.query", "{       \"query\": {\"match_all\": {  }}}");

        Job job = Job.getInstance(conf, ESToHdfs.class.getName());
        // 设置作业驱动类
        job.setJarByClass(ESToHdfs.class);
        // 设置ES的输入类型
        job.setInputFormatClass(EsInputFormat.class);

        job.setMapperClass(ESToHdfsMapper.class);

        job.setMapOutputKeyClass(NullWritable.class);
        job.setMapOutputValueClass(Text.class);

        FileOutputFormat.setOutputPath(job, new Path(out));

        job.setNumReduceTasks(0);

        return job.waitForCompletion(true) ? 0 : 1;
    }
}
  • 验证
    结果如下图

3)、示例2:tomcat_log_2023-03

将ES中的tomcat_log_2023-03索引数据存储至hdfs中,其中hdfs是HA。hdfs中是以txt形式存储的,其中数据用逗号隔离

  • 其数据结构
key Uzm_44YBH2rQ2w9r5vqK , value {message=2023-03-15 13:30:00.001 [schedulerJobAllTask_Worker-1] INFO c.o.d.s.t.QuartzTask.executeAllTaskList-{37} - 生成消息记录任务停止执行结束*******, tags=[_dateparsefailure], class=c.o.d.s.t.QuartzTask.executeAllTaskList-{37}, level=INFO, date=2023-03-15 13:30:00.001, thread=schedulerJobAllTask_Worker-1, fields={source=catalina}, @timestamp=2023-03-15T05:30:06.812Z, log={file={path=/opt/apache-tomcat-9.0.43/logs/catalina.out}, offset=76165371}, info=- 生成消息记录任务停止执行结束*******}
  • 实现
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.elasticsearch.hadoop.mr.EsInputFormat;
import org.elasticsearch.hadoop.mr.LinkedMapWritable;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ESToHdfs2 extends Configured implements Tool {
    private static String out = "/ES-Hadoop/tomcatlog";

    static class ESToHdfs2Mapper extends Mapper<Text, LinkedMapWritable, NullWritable, Text> {
        Text outValue = new Text();

        protected void map(Text key, LinkedMapWritable value, Context context) throws IOException, InterruptedException {
//            log.info("key {} , value {}", key.toString(), value);
            TomcatLog tLog = new TomcatLog();
            Iterator it = value.entrySet().iterator();
            String name = null;
            String data = null;
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                name = entry.getKey().toString();
                data = entry.getValue().toString();
                switch (name) {
                case "date":
                    tLog.setDate(data.replace('/', '-'));
                    break;
                case "thread":
                    tLog.setThread(data);
                    break;
                case "level":
                    tLog.setLogLevel(data);
                    break;
                case "class":
                    tLog.setClazz(data);
                    break;
                case "info":
                    tLog.setLogMsg(data);
                    break;
                }
            }
            outValue.set(tLog.toString());
            context.write(NullWritable.get(), outValue);
        }
    }

    @Data
    static class TomcatLog {
        private String date;
        private String thread;
        private String logLevel;
        private String clazz;
        private String logMsg;

        public String toString() {
            return new StringBuilder(date).append(",").append(thread).append(",").append(logLevel).append(",").append(clazz).append(",").append(logMsg).toString();
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        int status = ToolRunner.run(conf, new ESToHdfs2(), args);
        System.exit(status);
    }

    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        conf.set("fs.defaultFS", "hdfs://HadoopHAcluster");
        conf.set("dfs.nameservices", "HadoopHAcluster");
        conf.set("dfs.ha.namenodes.HadoopHAcluster", "nn1,nn2");
        conf.set("dfs.namenode.rpc-address.HadoopHAcluster.nn1", "server1:8020");
        conf.set("dfs.namenode.rpc-address.HadoopHAcluster.nn2", "server2:8020");
        conf.set("dfs.client.failover.proxy.provider.HadoopHAcluster", "org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider");
        System.setProperty("HADOOP_USER_NAME", "alanchan");

        conf.setBoolean("mapred.map.tasks.speculative.execution", false);
        conf.setBoolean("mapred.reduce.tasks.speculative.execution", false);
        conf.set("es.nodes", "server1:9200,server2:9200,server3:9200");
        // ElaticSearch 索引名称
        conf.set("es.resource", "tomcat_log_2023-03");
        conf.set("es.query", "{\"query\":{\"bool\":{\"must\":[{\"match_all\":{}}],\"must_not\":[],\"should\":[]}},\"from\":0,\"size\":10,\"sort\":[],\"aggs\":{}}");

        Job job = Job.getInstance(conf, ESToHdfs2.class.getName());
        // 设置作业驱动类
        job.setJarByClass(ESToHdfs2.class);
        job.setInputFormatClass(EsInputFormat.class);

        job.setMapperClass(ESToHdfs2Mapper.class);

        job.setMapOutputKeyClass(NullWritable.class);
        job.setMapOutputValueClass(Text.class);

        FileOutputFormat.setOutputPath(job, new Path(out));

        job.setNumReduceTasks(0);

        return job.waitForCompletion(true) ? 0 : 1;
    }

}
  • 验证
  • 9、Elasticsearch7.6.1 ES与HDFS相互转存数据-ES-Hadoop_日志分析_04


2、json文件格式写入

将ES中的tomcat_log_2023-03索引数据存储至hdfs中,其中hdfs是HA。hdfs中是以json形式存储的

  • 其数据结构
key Uzm_44YBH2rQ2w9r5vqK , value {message=2023-03-15 13:30:00.001 [schedulerJobAllTask_Worker-1] INFO c.o.d.s.t.QuartzTask.executeAllTaskList-{37} - 生成消息记录任务停止执行结束*******, tags=[_dateparsefailure], class=c.o.d.s.t.QuartzTask.executeAllTaskList-{37}, level=INFO, date=2023-03-15 13:30:00.001, thread=schedulerJobAllTask_Worker-1, fields={source=catalina}, @timestamp=2023-03-15T05:30:06.812Z, log={file={path=/opt/apache-tomcat-9.0.43/logs/catalina.out}, offset=76165371}, info=- 生成消息记录任务停止执行结束*******}
  • 实现
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.elasticsearch.hadoop.mr.EsInputFormat;
import org.elasticsearch.hadoop.mr.LinkedMapWritable;

import com.google.gson.Gson;

import lombok.Data;

  
public class ESToHdfsByJson extends Configured implements Tool {
    private static String out = "/ES-Hadoop/tomcatlog_json";

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        int status = ToolRunner.run(conf, new ESToHdfsByJson(), args);
        System.exit(status);
    }

    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        conf.set("fs.defaultFS", "hdfs://HadoopHAcluster");
        conf.set("dfs.nameservices", "HadoopHAcluster");
        conf.set("dfs.ha.namenodes.HadoopHAcluster", "nn1,nn2");
        conf.set("dfs.namenode.rpc-address.HadoopHAcluster.nn1", "server1:8020");
        conf.set("dfs.namenode.rpc-address.HadoopHAcluster.nn2", "server2:8020");
        conf.set("dfs.client.failover.proxy.provider.HadoopHAcluster", "org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider");
        System.setProperty("HADOOP_USER_NAME", "alanchan");

        conf.setBoolean("mapred.map.tasks.speculative.execution", false);
        conf.setBoolean("mapred.reduce.tasks.speculative.execution", false);
        conf.set("es.nodes", "server1:9200,server2:9200,server3:9200");
        // ElaticSearch 索引名称
        conf.set("es.resource", "tomcat_log_2023-03");
        conf.set("es.query", "{\"query\":{\"bool\":{\"must\":[{\"match_all\":{}}],\"must_not\":[],\"should\":[]}},\"from\":0,\"size\":10,\"sort\":[],\"aggs\":{}}");

        Job job = Job.getInstance(conf, ESToHdfs2.class.getName());
        // 设置作业驱动类
        job.setJarByClass(ESToHdfsByJson.class);
        job.setInputFormatClass(EsInputFormat.class);

        job.setMapperClass(ESToHdfsByJsonMapper.class);

        job.setMapOutputKeyClass(NullWritable.class);
        job.setMapOutputValueClass(Text.class);

        FileOutputFormat.setOutputPath(job, new Path(out));

        job.setNumReduceTasks(0);

        return job.waitForCompletion(true) ? 0 : 1;
    }

    static class ESToHdfsByJsonMapper extends Mapper<Text, LinkedMapWritable, NullWritable, Text> {
        Text outValue = new Text();
        private Gson gson = new Gson();
        
        protected void map(Text key, LinkedMapWritable value, Context context) throws IOException, InterruptedException {
//            log.info("key {} , value {}", key.toString(), value);
            TomcatLog tLog = new TomcatLog();
//            tLog.setId(key.toString());
            Iterator it = value.entrySet().iterator();
            String name = null;
            String data = null;
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                name = entry.getKey().toString();
                data = entry.getValue().toString();
                switch (name) {
                case "date":
                    tLog.setDate(data.replace('/', '-'));
                    break;
                case "thread":
                    tLog.setThread(data);
                    break;
                case "level":
                    tLog.setLogLevel(data);
                    break;
                case "class":
                    tLog.setClazz(data);
                    break;
                case "info":
                    tLog.setLogMsg(data);
                    break;
                }
            }
            outValue.set(gson.toJson(tLog));
            context.write(NullWritable.get(), outValue);
        }

    }

    @Data
    static class TomcatLog {
//        private String id ;
        private String date;
        private String thread;
        private String logLevel;
        private String clazz;
        private String logMsg;

    }
}
  • 验证
  • 9、Elasticsearch7.6.1 ES与HDFS相互转存数据-ES-Hadoop_日志分析_05


三、HDFS写入ES

本示例以上述例子中存入hdfs的数据。经过测试,ES只能将json的数据导入。
pom.xml参考上述例子

1、txt文件写入

先将数据转换成json后存入

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.elasticsearch.hadoop.mr.EsOutputFormat;

import com.google.gson.Gson;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class HdfsTxtDataToES extends Configured implements Tool {
    private static String out = "/ES-Hadoop/tomcatlog";

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        int status = ToolRunner.run(conf, new HdfsTxtDataToES(), args);
        System.exit(status);
    }

    @Data
    static class TomcatLog {
        private String date;
        private String thread;
        private String logLevel;
        private String clazz;
        private String logMsg;
    }

    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        conf.set("fs.defaultFS", "hdfs://HadoopHAcluster");
        conf.set("dfs.nameservices", "HadoopHAcluster");
        conf.set("dfs.ha.namenodes.HadoopHAcluster", "nn1,nn2");
        conf.set("dfs.namenode.rpc-address.HadoopHAcluster.nn1", "server1:8020");
        conf.set("dfs.namenode.rpc-address.HadoopHAcluster.nn2", "server2:8020");
        conf.set("dfs.client.failover.proxy.provider.HadoopHAcluster", "org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider");
        System.setProperty("HADOOP_USER_NAME", "alanchan");

        conf.setBoolean("mapred.map.tasks.speculative.execution", false);
        conf.setBoolean("mapred.reduce.tasks.speculative.execution", false);
        conf.set("es.nodes", "server1:9200,server2:9200,server3:9200");

        // ElaticSearch 索引名称,可以不提前创建
        conf.set("es.resource", "tomcat_log_2024");
        // Hadoop上的数据格式为JSON,可以直接导入
        conf.set("es.input.json", "yes");

        Job job = Job.getInstance(conf, HdfsTxtDataToES.class.getName());
        // 设置作业驱动类
        job.setJarByClass(HdfsTxtDataToES.class);
        // 设置EsOutputFormat
        job.setOutputFormatClass(EsOutputFormat.class);

        job.setMapperClass(HdfsTxtDataToESMapper.class);

        job.setMapOutputKeyClass(NullWritable.class);
        job.setMapOutputValueClass(Text.class);

        FileInputFormat.setInputPaths(job, new Path(out));

        job.setNumReduceTasks(0);

        return job.waitForCompletion(true) ? 0 : 1;
    }

    static class HdfsTxtDataToESMapper extends Mapper<LongWritable, Text, NullWritable, Text> {
        Text outValue = new Text();
        TomcatLog tLog = new TomcatLog();
        Gson gson = new Gson();

        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            log.info("key={},value={}", key, value);
            // date:2023-03-13 17:33:00.001,
            // thread:schedulerJobAllTask_Worker-1,
            // loglevel:INFO,
            // clazz:o.q.c.QuartzScheduler.start-{461},
            // logMsg:- Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
            String[] lines = value.toString().split(",");
            tLog.setDate(lines[0]);
            tLog.setThread(lines[1]);
            tLog.setLogLevel(lines[2]);
            tLog.setClazz(lines[3]);
            tLog.setLogMsg(lines[4]);
            outValue.set(gson.toJson(tLog));
            context.write(NullWritable.get(), outValue);
        }
    }
}

2、json文件写入

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.elasticsearch.hadoop.mr.EsOutputFormat;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HdfsJsonDataToES extends Configured implements Tool {
    private static String out = "/ES-Hadoop/tomcatlog_json";

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        int status = ToolRunner.run(conf, new HdfsJsonDataToES(), args);
        System.exit(status);
    }

    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        conf.set("fs.defaultFS", "hdfs://HadoopHAcluster");
        conf.set("dfs.nameservices", "HadoopHAcluster");
        conf.set("dfs.ha.namenodes.HadoopHAcluster", "nn1,nn2");
        conf.set("dfs.namenode.rpc-address.HadoopHAcluster.nn1", "server1:8020");
        conf.set("dfs.namenode.rpc-address.HadoopHAcluster.nn2", "server2:8020");
        conf.set("dfs.client.failover.proxy.provider.HadoopHAcluster", "org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider");
        System.setProperty("HADOOP_USER_NAME", "alanchan");

        conf.setBoolean("mapred.map.tasks.speculative.execution", false);
        conf.setBoolean("mapred.reduce.tasks.speculative.execution", false);
        conf.set("es.nodes", "server1:9200,server2:9200,server3:9200");

        // ElaticSearch 索引名称,可以不提前创建
        conf.set("es.resource", "tomcat_log_2023");
        //Hadoop上的数据格式为JSON,可以直接导入
        conf.set("es.input.json", "yes");
        
        Job job = Job.getInstance(conf, HdfsJsonDataToES.class.getName());
        // 设置作业驱动类
        job.setJarByClass(HdfsJsonDataToES.class);
        job.setOutputFormatClass(EsOutputFormat.class);

        job.setMapperClass(HdfsJsonDataToESMapper.class);

        job.setMapOutputKeyClass(NullWritable.class);
        job.setMapOutputValueClass(Text.class);

        FileInputFormat.setInputPaths(job, new Path(out));

        job.setNumReduceTasks(0);

        return job.waitForCompletion(true) ? 0 : 1;
    }

    static class HdfsJsonDataToESMapper extends Mapper<LongWritable, Text, NullWritable, Text> {
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            log.info("key={},value={}",key,value);
            context.write(NullWritable.get(), value);
        }
    }
}

以上,简单的介绍了ES-hadoop组件功能使用,即通过ES-hadoop实现相互数据写入示例。




标签:HDFS,set,Elasticsearch7.6,hadoop,conf,org,apache,import,ES
From: https://blog.51cto.com/alanchan2win/6598257

相关文章

  • pytest + yaml 框架 -42.支持 mock 功能
    前言前面已经通过代理实现了抓包自动生成yaml用例的功能,通过代理也可以实现mock功能。mock有2种场景:1.直接拦截发出去的请求,还未到达服务端,模拟自定义返回结果2.发出去的请求,服务端有反回,拦截返回的结果,篡改返回内容,模拟自己需要的数据拦截发出去的请求先看第一种场景:直接......
  • nested exception is java.sql.SQLException: connection disabled
    标题:解决SpringBoot连接数据库出现"connectiondisabled"异常在使用SpringBoot连接数据库时,有时候会遇到"nestedexceptionisjava.sql.SQLException:connectiondisabled"异常。这个异常通常是由以下原因引起的:数据库连接配置错误:检查数据库连接的URL、用户名和密码是否正确配......
  • MySQL批量新增或修改时出现异常: Lock wait timeout exceeded; try restarting transact
    标题:解决MySQL批量新增或修改时出现"nestedexceptionisjava.sql.SQLException:Lockwaittimeoutexceeded;tryrestartingtransaction"异常摘要在使用MySQL数据库进行批量新增或修改操作时,有时候会遇到"nestedexceptionisjava.sql.SQLException:Lockwaittimeoutexcee......
  • kubeskoop 阿里开源的k8s 网络分析工具
    kubeskoop是阿里开源的k8s网络分析工具,提供了一个完整的k8s网络分析工具集,可以快速帮助我们分析容器网络问题,支持不少cni插件参考图 说明kubeskoop技术上利用了ebpf,功能还是很强大的,同时提供了可视化ui工具,是一个很不错的k8s网络分析工具,很值得使用下参考资料https:......
  • Atcoder Beginner Contest 251-260 EFG
    #251E-TakahashiandAnimals*1261,*环形dpACLink考虑环形dp,对于使用或者不使用\(1\)号饲料分别dp,然后取最小值即可。......
  • Japanese Student Championship 2021 F Max Matrix
    洛谷传送门AtCoder传送门我们考虑动态维护答案。如果已经知道上一步的答案,考虑计算这一次操作之后答案的变化。考虑现在有一个数列\(a_{1\simn}\),我们想知道\(\sum\limits_{i=1}^n\max(x,a_i)\)。计算出\(c=\sum\limits_{i=1}^n[a_i<x],s=\sum\limits_{i......
  • Educational Codeforces Round 151 F. Swimmers in the Pool
    一.前言本来打算打打这个比赛玩玩,结果同学找我打游戏王去了,就没打现场(逃)因为是一道不错的数学题,来写写补题的题解这里点名批评@HOLIC喂给我的假题意,让我查错大半天,最后发现题意错了还重新推了好多东西,拳头都硬了等会儿顺便分享下假题意的一种做法二.正文简单题意:有n个......
  • CodeForces 1845C Strong Password
    洛谷传送门CF传送门我怎么这么多天没写题解了,快来水一篇。考虑对\(s\)串建子序列自动机后dp。设\(n=|s|\)。建子序列自动机,就是求出\(nxt_{i,j}\)为\([i,n]\)中第一个等于\(j\)的位置,不存在则\(nxt_{i,j}=n+1\)。然后我们设\(f_{i,j}\)为填到密码的......
  • Redis Desktop Manager(Redis可视化工具)安装及使用教程
    RedisDesktopManager(Redis可视化工具)安装及使用教程2、一、工具/材料官网下载:https://redisdesktop.com/download百度网盘:https://pan.baidu.com/s/15xVRpCT8mkP2uT8PoBHT3g提取码:v727二、方法/步骤1.说明RedisDesktopManager是一款简单快速、跨平台的Redis桌面管理工具,也被......
  • postgresql数据库查看表结构
      2、 ......