HBase客戶(hù)端API-表操作

上一篇博客說(shuō)了使用 HBase 的客戶(hù)端 API 來(lái)操作管理 HBase 中的表弦追,今天我們看看怎樣通過(guò) API 來(lái)操作表中的數(shù)據(jù)予颤。

介紹

在 HBase 中對(duì)數(shù)據(jù)表中的數(shù)據(jù)的操做我們一般是通過(guò) Table缰趋, Put总放, Get, Delete谷浅,Scan扒俯,Result等幾個(gè)類(lèi)來(lái)實(shí)現(xiàn)奶卓。

  • Table 是表對(duì)象,對(duì)應(yīng)數(shù)據(jù)庫(kù)中的一張表撼玄,我們可以在表上執(zhí)行添加夺姑,修改,刪除和查詢(xún)操作掌猛。
  • Put 主要是用了對(duì)數(shù)據(jù)表中的記錄執(zhí)行寫(xiě)入/更新操作瑟幕。
  • Get 主要是用了對(duì)數(shù)據(jù)表中的記錄執(zhí)行查詢(xún)操作。
  • Delete 主要是用了對(duì)數(shù)據(jù)表中的記錄執(zhí)行查詢(xún)操作留潦。
  • Scan 用來(lái)在數(shù)據(jù)表中執(zhí)行查詢(xún)操作只盹。
  • Result 用來(lái)保存查詢(xún)的結(jié)果記錄。

寫(xiě)入數(shù)據(jù)操作

  • 在寫(xiě)入數(shù)據(jù)時(shí)兔院,我們需要首先獲取到需要操作的Table對(duì)象殖卑。
  • 然后創(chuàng)建一個(gè)Put對(duì)象來(lái)執(zhí)行更新操作,創(chuàng)建對(duì)象時(shí)需要給定一個(gè)行名坊萝。
  • 然后在Put對(duì)象中添加需要執(zhí)行的操作孵稽,這里是添加數(shù)據(jù)。
  • 數(shù)據(jù)填充完后十偶,在表上執(zhí)行put操作菩鲜。
  • 最后,不要忘了關(guān)閉表惦积。
    private void putRow(String row, String username, String password, String home, String office) throws IOException {
        Table table = connection.getTable(TableName.valueOf("user"));
        Put put = new Put(Bytes.toBytes(row));
        put.addColumn(Bytes.toBytes("base"), Bytes.toBytes("username"), Bytes.toBytes(username));
        put.addColumn(Bytes.toBytes("base"), Bytes.toBytes("password"), Bytes.toBytes(password));
        put.addColumn(Bytes.toBytes("address"), Bytes.toBytes("home"), Bytes.toBytes(home));
        put.addColumn(Bytes.toBytes("address"), Bytes.toBytes("office"), Bytes.toBytes(office));
        table.put(put);
        table.close();
    }

獲取數(shù)據(jù)

  • 需要獲取到需要操作的Table對(duì)象接校。
  • 創(chuàng)建Get對(duì)象來(lái)執(zhí)行獲取操作,創(chuàng)建Get對(duì)象的時(shí)候需要告訴它是要獲取哪一行數(shù)據(jù)狮崩。
  • 然后在表上執(zhí)行g(shù)et操作來(lái)獲取數(shù)據(jù)蛛勉。
  • 取到數(shù)據(jù)后,數(shù)據(jù)是保持在Result對(duì)象中睦柴,我們可以通過(guò)Result對(duì)象的一些方法來(lái)取得需要的值诽凌。
  • 最后,不要忘了關(guān)閉表坦敌。
    private void getRow(String row) throws IOException {
        Table table = connection.getTable(TableName.valueOf("user"));
        Get get = new Get(Bytes.toBytes(row));
        Result result = table.get(get);
        if (Bytes.toString(result.getRow()) != null) {
            StringBuilder sb = new StringBuilder();
            sb.append(Bytes.toString(result.getRow()));
            sb.append("[");
            sb.append("base:username=" + Bytes.toString(result.getValue(Bytes.toBytes("base"), Bytes.toBytes("username"))));
            sb.append(", base:password=" + Bytes.toString(result.getValue(Bytes.toBytes("base"), Bytes.toBytes("password"))));
            sb.append(", address:home=" + Bytes.toString(result.getValue(Bytes.toBytes("address"), Bytes.toBytes("home"))));
            sb.append(", address:office=" + Bytes.toString(result.getValue(Bytes.toBytes("address"), Bytes.toBytes("office"))));
            sb.append("]");
            System.out.println(sb.toString());
        }
        table.close();
    }

刪除數(shù)據(jù)

  • 需要獲取到需要操作的Table對(duì)象侣诵。
  • 創(chuàng)建Delete對(duì)象來(lái)執(zhí)行刪除操作,創(chuàng)建Delete對(duì)象的時(shí)候需要告訴它是要?jiǎng)h除哪一行數(shù)據(jù)狱窘。
  • 然后在表上執(zhí)行delete操作來(lái)刪除數(shù)據(jù)杜顺。
  • 最后,不要忘了關(guān)閉表训柴。
    private void deleteRow(String row) throws IOException {
        Table table = connection.getTable(TableName.valueOf("user"));
        Delete delete = new Delete(Bytes.toBytes(row));
        table.delete(delete);
        table.close();
    }

查詢(xún)數(shù)據(jù)

  • 需要獲取到需要操作的Table對(duì)象哑舒。
  • 創(chuàng)建Scan對(duì)象來(lái)執(zhí)行查詢(xún)操作。
  • 然后在表上執(zhí)行scan操作并得到ResultScanner對(duì)象幻馁。
  • 然后我們?cè)赗esultScanner上執(zhí)行迭代操作來(lái)獲取其中的值洗鸵。
  • 最后越锈,不要忘了關(guān)閉表。
    private void getRows() throws IOException {
        Table table = connection.getTable(TableName.valueOf("user"));
        Scan scan = new Scan();
        ResultScanner resultScanner = table.getScanner(scan);
        Iterator<Result> it = resultScanner.iterator();
        while (it.hasNext()) {
            Result result = it.next();
            getRow(result);
        }
        table.close();
    }

完整代碼

最后是完整的執(zhí)行數(shù)據(jù)庫(kù)操作的例子代碼膘滨。

package my.hbasestudy;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class TestAPI {

    private static final String TABLE_NAME = "user";

    private static final String COLUMN_FAMILY_BASE = "base";
    private static final String COLUMN_FAMILY_ADDRESS = "address";

    private static final String COLUMN_USERNAME = "username";
    private static final String COLUMN_PASSWORD = "password";
    private static final String COLUMN_HOME = "home";
    private static final String COLUMN_OFFICE = "office";

    private Connection connection;

    public static void main(String[] args) throws Exception {
        Configuration config = HBaseConfiguration.create();
        Connection connection = ConnectionFactory.createConnection(config);

        long t1 = System.currentTimeMillis();

        TestAPI t = new TestAPI(connection);

        t.listTable();

        t.createTable();
        t.listTable();

        t.putRows();
        t.getRows();

        t.deleteRows();
        t.getRows();

        t.deleteTable();

        long t2 = System.currentTimeMillis();
        System.out.println("Time: " + (t2 - t1));

        connection.close();
    }

    public TestAPI(Connection connection) {
        this.connection = connection;
    }

    private void listTable() throws IOException {
        Admin admin = connection.getAdmin();

        try {
            List<TableDescriptor> tableDescriptors = admin.listTableDescriptors();
            for (TableDescriptor tableDescriptor : tableDescriptors) {
                TableName tableName = tableDescriptor.getTableName();
                System.out.println("Table: " + tableName);
                System.out.println("\texists: " + admin.tableExists(tableName));
                System.out.println("\tenabled: " + admin.isTableEnabled(tableName));
            }
        } finally {
            admin.close();
        }
    }

    private void createTable() throws IOException {
        Admin admin = connection.getAdmin();

        try {
            TableDescriptor tableDesc = TableDescriptorBuilder.newBuilder(TableName.valueOf(TABLE_NAME))
                    .addColumnFamily(ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(COLUMN_FAMILY_BASE)).build())
                    .addColumnFamily(ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(COLUMN_FAMILY_ADDRESS)).build())
                    .build();
            admin.createTable(tableDesc);
        } finally {
            admin.close();
        }
    }

    private void deleteTable() throws IOException {
        Admin admin = connection.getAdmin();

        try {
            admin.disableTable(TableName.valueOf(TABLE_NAME));
            admin.deleteTable(TableName.valueOf(TABLE_NAME));
        } finally {
            admin.close();
        }
    }

    private void putRows() throws IOException {
        for (int i = 0; i < 10; i++) {
            putRow("row_" + i, "user_" + i, "password_" + i, "home_" + i, "office_" + i);
        }
    }

    private void putRow(String row, String username, String password, String home, String office) throws IOException {
        Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
        Put put = new Put(Bytes.toBytes(row));
        put.addColumn(Bytes.toBytes(COLUMN_FAMILY_BASE), Bytes.toBytes(COLUMN_USERNAME), Bytes.toBytes(username));
        put.addColumn(Bytes.toBytes(COLUMN_FAMILY_BASE), Bytes.toBytes(COLUMN_PASSWORD), Bytes.toBytes(password));
        put.addColumn(Bytes.toBytes(COLUMN_FAMILY_ADDRESS), Bytes.toBytes(COLUMN_HOME), Bytes.toBytes(home));
        put.addColumn(Bytes.toBytes(COLUMN_FAMILY_ADDRESS), Bytes.toBytes(COLUMN_OFFICE), Bytes.toBytes(office));
        table.put(put);
        table.close();
    }

    private void getRows() throws IOException {
        Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
        Scan scan = new Scan();
        ResultScanner resultScanner = table.getScanner(scan);
        Iterator<Result> it = resultScanner.iterator();
        while (it.hasNext()) {
            Result result = it.next();
            getRow(result);
        }
        table.close();
    }

    private void getRow(String row) throws IOException {
        Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
        Get get = new Get(Bytes.toBytes(row));
        Result result = table.get(get);
        getRow(result);
        table.close();
    }

    private void getRow(Result result) {
        if (Bytes.toString(result.getRow()) != null) {
            StringBuilder sb = new StringBuilder();
            sb.append(Bytes.toString(result.getRow()));
            sb.append("[");
            sb.append("base:username=" + Bytes.toString(result.getValue(Bytes.toBytes("base"), Bytes.toBytes("username"))));
            sb.append(", base:password=" + Bytes.toString(result.getValue(Bytes.toBytes("base"), Bytes.toBytes("password"))));
            sb.append(", address:home=" + Bytes.toString(result.getValue(Bytes.toBytes("address"), Bytes.toBytes("home"))));
            sb.append(", address:office=" + Bytes.toString(result.getValue(Bytes.toBytes("address"), Bytes.toBytes("office"))));
            sb.append("]");
            System.out.println(sb.toString());
        }
    }

    private void deleteRows() throws IOException {
        Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
        Scan scan = new Scan();
        ResultScanner resultScanner = table.getScanner(scan);
        Iterator<Result> it = resultScanner.iterator();
        while (it.hasNext()) {
            Result result = it.next();
            Delete delete = new Delete(result.getRow());
            table.delete(delete);
        }
        table.close();
    }

    private void deleteRow(String row) throws IOException {
        Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
        Delete delete = new Delete(Bytes.toBytes(row));
        table.delete(delete);
        table.close();
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末甘凭,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子火邓,更是在濱河造成了極大的恐慌丹弱,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,084評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件铲咨,死亡現(xiàn)場(chǎng)離奇詭異躲胳,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)纤勒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén)坯苹,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人摇天,你說(shuō)我怎么就攤上這事粹湃∏牵” “怎么了锯玛?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,450評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵奔则,是天一觀的道長(zhǎng)撒汉。 經(jīng)常有香客問(wèn)我,道長(zhǎng)承粤,這世上最難降的妖魔是什么择葡? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,322評(píng)論 1 293
  • 正文 為了忘掉前任约巷,我火速辦了婚禮记某,結(jié)果婚禮上司训,老公的妹妹穿的比我還像新娘。我一直安慰自己液南,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,370評(píng)論 6 390
  • 文/花漫 我一把揭開(kāi)白布勾徽。 她就那樣靜靜地躺著滑凉,像睡著了一般。 火紅的嫁衣襯著肌膚如雪喘帚。 梳的紋絲不亂的頭發(fā)上畅姊,一...
    開(kāi)封第一講書(shū)人閱讀 51,274評(píng)論 1 300
  • 那天,我揣著相機(jī)與錄音吹由,去河邊找鬼若未。 笑死,一個(gè)胖子當(dāng)著我的面吹牛倾鲫,可吹牛的內(nèi)容都是我干的粗合。 我是一名探鬼主播萍嬉,決...
    沈念sama閱讀 40,126評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼隙疚!你這毒婦竟也來(lái)了壤追?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 38,980評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤供屉,失蹤者是張志新(化名)和其女友劉穎行冰,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體伶丐,經(jīng)...
    沈念sama閱讀 45,414評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡悼做,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,599評(píng)論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了哗魂。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片贿堰。...
    茶點(diǎn)故事閱讀 39,773評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖啡彬,靈堂內(nèi)的尸體忽然破棺而出羹与,到底是詐尸還是另有隱情,我是刑警寧澤庶灿,帶...
    沈念sama閱讀 35,470評(píng)論 5 344
  • 正文 年R本政府宣布纵搁,位于F島的核電站,受9級(jí)特大地震影響往踢,放射性物質(zhì)發(fā)生泄漏腾誉。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,080評(píng)論 3 327
  • 文/蒙蒙 一峻呕、第九天 我趴在偏房一處隱蔽的房頂上張望利职。 院中可真熱鬧,春花似錦瘦癌、人聲如沸猪贪。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,713評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)热押。三九已至,卻和暖如春斤寇,著一層夾襖步出監(jiān)牢的瞬間桶癣,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,852評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工娘锁, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留牙寞,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,865評(píng)論 2 370
  • 正文 我出身青樓莫秆,卻偏偏與公主長(zhǎng)得像间雀,于是被迫代替她去往敵國(guó)和親悔详。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,689評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容