簡體   English   中英

檢查表是否存在

[英]Check if table exists

檢查 Hbase 表是否存在的最快方法是什么? 看着這個api:

http://hbase.apache.org/devapidocs/org/apache/hadoop/hbase/client/HBaseAdmin.html 以下哪個是最快的:

  1. 表存在
  2. isTableEnabled
  3. isTableAvailable
  4. 列表

使用#4,您可以獲得所有表的列表並對其進行迭代並比較這些表中的一個是否與您的表名匹配。

或者還有另一種更聰明的方法?

這是我的示例代碼。 (斯卡拉)

import org.apache.hadoop.hbase.HBaseConfiguration

var TableName = "sample"
val conf = HBaseConfiguration.create()
var hbaseAdmin = new HBaseAdmin(conf)
if (!hbaseAdmin.tableExists(TableName)) {
  println(TableName + " Does Not Exist")
}

在這里,你只需要使用“tableExists”來檢查這個TableName是否存在。

  HBaseAdmin hba = new HBaseAdmin(hbaseTemplate.getConfiguration());
    if (hba.tableExists(tableName) == false) {

        HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);
        HColumnDescriptor columnDescriptor = new HColumnDescriptor(columnFamilyProfile);
        tableDescriptor.addFamily(columnDescriptor);

        hba.createTable(tableDescriptor);
    }

使用 HBaseAdmin.tableExists 只需要大約 500 毫秒來檢查表是否存在。 我們的集群中只有兩個節點,所以它可能取決於集群的大小,但它似乎並沒有不合理地慢。

您可以嘗試打開一個HTable到該表,並且(我認為)如果該表不存在,它將拋出異常/錯誤(尚未工作,因此無法進行快速測試)。

這不是 100% 會奏效,只是一個腦洞大開的想法。 :)

每次啟動我的應用程序時,我都必須檢查表是否存在。 我在一個配置類中做了這個,使用 spring boot

這是代碼,希望它有所幫助。

@Configuration
public class CustomHbaseConfiguration {

@Bean
public Connection hbaseConnection() throws IOException {
    // Create connection
    final org.apache.hadoop.conf.Configuration configuration = HBaseConfiguration.create();

    // Validate that Hbase is available
    HBaseAdmin.available(configuration);

    // return the hbaseConnection Bean
    return ConnectionFactory.createConnection(configuration);
}



@PostConstruct
public void hbaseTableLogic() throws IOException {

    // With the hbaseConnection bean, get the HbaseAdmin instance
    Admin admin = hbaseConnection().getAdmin();

    // The name of my table
    TableName YOUR_TABLE_NAME_HERE = TableName.valueOf("PUT_YOUR_TABLE_NAME_HERE");

    // Check if the table already exists ? else : create table and colum family
    if (!admin.tableExists(YOUR_TABLE_NAME_HERE)) {
        HTableDescriptor hTableDescriptor = new HTableDescriptor(YOUR_TABLE_NAME_HERE);
        hTableDescriptor.addFamily(new HColumnDescriptor("PUT_YOUR_COLUM_FAMILY_HERE"));
        admin.createTable(hTableDescriptor);
    }
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM