001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.mapreduce;
019
020import java.io.IOException;
021import java.util.TreeMap;
022import org.apache.hadoop.conf.Configuration;
023import org.apache.hadoop.conf.Configured;
024import org.apache.hadoop.hbase.HBaseConfiguration;
025import org.apache.hadoop.hbase.client.Put;
026import org.apache.hadoop.hbase.client.Result;
027import org.apache.hadoop.hbase.client.Scan;
028import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
029import org.apache.hadoop.hbase.util.Bytes;
030import org.apache.hadoop.mapreduce.Job;
031import org.apache.hadoop.mapreduce.Mapper;
032import org.apache.hadoop.util.Tool;
033import org.apache.hadoop.util.ToolRunner;
034import org.apache.yetus.audience.InterfaceAudience;
035
036/**
037 * Example map/reduce job to construct index tables that can be used to quickly find a row based on
038 * the value of a column. It demonstrates:
039 * <ul>
040 * <li>Using TableInputFormat and TableMapReduceUtil to use an HTable as input to a map/reduce
041 * job.</li>
042 * <li>Passing values from main method to children via the configuration.</li>
043 * <li>Using MultiTableOutputFormat to output to multiple tables from a map/reduce job.</li>
044 * <li>A real use case of building a secondary index over a table.</li>
045 * </ul>
046 * <h3>Usage</h3>
047 * <p>
048 * Modify ${HADOOP_HOME}/conf/hadoop-env.sh to include the hbase jar, the zookeeper jar (can be
049 * found in lib/ directory under HBase root, the examples output directory, and the hbase conf
050 * directory in HADOOP_CLASSPATH, and then run
051 * <tt><strong>bin/hadoop org.apache.hadoop.hbase.mapreduce.IndexBuilder
052 *  TABLE_NAME COLUMN_FAMILY ATTR [ATTR ...]</strong></tt>
053 * </p>
054 * <p>
055 * To run with the sample data provided in index-builder-setup.rb, use the arguments
056 * <strong><tt>people attributes name email phone</tt></strong>.
057 * </p>
058 * <p>
059 * This code was written against HBase 0.21 trunk.
060 * </p>
061 */
062@InterfaceAudience.Private
063public class IndexBuilder extends Configured implements Tool {
064  /** the column family containing the indexed row key */
065  public static final byte[] INDEX_COLUMN = Bytes.toBytes("INDEX");
066  /** the qualifier containing the indexed row key */
067  public static final byte[] INDEX_QUALIFIER = Bytes.toBytes("ROW");
068
069  /**
070   * Internal Mapper to be run by Hadoop.
071   */
072  public static class Map
073    extends Mapper<ImmutableBytesWritable, Result, ImmutableBytesWritable, Put> {
074    private byte[] family;
075    private TreeMap<byte[], ImmutableBytesWritable> indexes;
076
077    @Override
078    protected void map(ImmutableBytesWritable rowKey, Result result, Context context)
079      throws IOException, InterruptedException {
080      for (java.util.Map.Entry<byte[], ImmutableBytesWritable> index : indexes.entrySet()) {
081        byte[] qualifier = index.getKey();
082        ImmutableBytesWritable tableName = index.getValue();
083        byte[] value = result.getValue(family, qualifier);
084        if (value != null) {
085          // original: row 123 attribute:phone 555-1212
086          // index: row 555-1212 INDEX:ROW 123
087          Put put = new Put(value);
088          put.addColumn(INDEX_COLUMN, INDEX_QUALIFIER, rowKey.get());
089          context.write(tableName, put);
090        }
091      }
092    }
093
094    @Override
095    protected void setup(Context context) throws IOException, InterruptedException {
096      Configuration configuration = context.getConfiguration();
097      String tableName = configuration.get("index.tablename");
098      String[] fields = configuration.getStrings("index.fields");
099      String familyName = configuration.get("index.familyname");
100      family = Bytes.toBytes(familyName);
101      indexes = new TreeMap<>(Bytes.BYTES_COMPARATOR);
102      for (String field : fields) {
103        // if the table is "people" and the field to index is "email", then the
104        // index table will be called "people-email"
105        indexes.put(Bytes.toBytes(field),
106          new ImmutableBytesWritable(Bytes.toBytes(tableName + "-" + field)));
107      }
108    }
109  }
110
111  /**
112   * Job configuration.
113   */
114  public static Job configureJob(Configuration conf, String[] args) throws IOException {
115    String tableName = args[0];
116    String columnFamily = args[1];
117    System.out.println("****" + tableName);
118    conf.set(TableInputFormat.SCAN, TableMapReduceUtil.convertScanToString(new Scan()));
119    conf.set(TableInputFormat.INPUT_TABLE, tableName);
120    conf.set("index.tablename", tableName);
121    conf.set("index.familyname", columnFamily);
122    String[] fields = new String[args.length - 2];
123    System.arraycopy(args, 2, fields, 0, fields.length);
124    conf.setStrings("index.fields", fields);
125    Job job = new Job(conf, tableName);
126    job.setJarByClass(IndexBuilder.class);
127    job.setMapperClass(Map.class);
128    job.setNumReduceTasks(0);
129    job.setInputFormatClass(TableInputFormat.class);
130    job.setOutputFormatClass(MultiTableOutputFormat.class);
131    return job;
132  }
133
134  @Override
135  public int run(String[] args) throws Exception {
136    Configuration conf = HBaseConfiguration.create(getConf());
137    if (args.length < 3) {
138      System.err.println("Only " + args.length + " arguments supplied, required: 3");
139      System.err.println("Usage: IndexBuilder <TABLE_NAME> <COLUMN_FAMILY> <ATTR> [<ATTR> ...]");
140      System.exit(-1);
141    }
142    Job job = configureJob(conf, args);
143    return (job.waitForCompletion(true) ? 0 : 1);
144  }
145
146  public static void main(String[] args) throws Exception {
147    int result = ToolRunner.run(HBaseConfiguration.create(), new IndexBuilder(), args);
148    System.exit(result);
149  }
150}