shell脚本操作hbase的命令

0.进入hbase shell

./hbase shell 
help 
help “get” #查看单独的某个命令的帮助

  1. status 查看状态
  2. version 查看版本

2.DDL(数据定义语言Data Definition Language)命令

1. 创建表

create ‘表名称’,’列名称1’,’列名称2’,’列名称3’ 

create 'member','member_id','address','info'

1.1 创建namespace(表空间相当于数据库

hbase(main):020:0> create_namespace 'cm'

1.2 创建表格和列族

hbase(main):020:0> create 'cm:mydemo','base'

2.列出所有的表

list ‘abc.*’ #显示abc开头的表

3.获得表的描述

describe ‘table_name’

Table play_error_file is ENABLEDplay_error_filecolumn families description{NAME => 'cf',BLOOMFILTER => 'ROW',#根据应用来定,看需要精确到rowkey还是column。bloom filter的作用是对一个region下查找记录所在的hfile有用。一个region下hfile数量越多,bloom filter的作用越明显。适合那种compaction(压缩)赶不上flush速度的应用。VERSIONS => '1',# 通常是3,对于更新比较频繁的应用可以设置为1IN_MEMORY => 'false',KEEP_DELETED_CELLS => 'FALSE',DATA_BLOCK_ENCODING => 'NONE',TTL => 'FOREVER',COMPRESSION => 'NONE',MIN_VERSIONS => '0',BLOCKCACHE =>'true',BLOCKSIZE => '65536',REPLICATION_SCOPE => '0'}

4.删除一个列族 alter,disable, enable

disable 'member'  #删除列族时必须先将表给disablealter 'member',{NAME=>'member_id',METHOD=>'delete'}#删除后继续enable 'member'enable 'member'

5.删除表

disable 'table_name'drop 'table_name'

6.查询表是否存在

exists 'table_name'

7.判断表是否enabled

is_enabled 'table_name'

3.DML(data manipulation language)操作

1.插入

在ns1:t1或者t1表里的r1行,c1列中插入值,ts1是时间

put 'ns1:t1', 'r1','c1','value'orput 't1','r1','c1','value'orput 't1','r1','c1','value',ts1orput 't1','r1','c1','value',{ATTRIBUTES=>{'mykey'=>'myvalue'}}put 't1','r1','c1','value',ts1,{ATTRIBUTES=>{'mykey'=>'myvalue'}}put 't1','r1','c1','value',ts1,{VISIBILITY=>'PRIVATE|SECRET}# t是table 't1'表的引用t.put 'r1','c1','value',ts1,{ATTRIBUTES=>{'mykey'=>'myvalue'}}put 'table_name','row_index','info:age','24'put 'table_name','row_index','info:birthday','1987-06-17'put 'table_name','row_index','info:company','tencent'put 'table_name','row_index','address:contry','china'put 'table_name','row_index','address:province','china'put 'table_name','row_index','address:city','shenzhen'

2.获取一条数据

# 获取一个id的所有数据get 'table_name','row_index'# 获取一个id,一个列族的所有数据get 'table_name','row_index','info'# 获取一个id,一个列族中一个列的所有数据get 'table_name','row_index','info:age'

3.更新一条记录

将qy的单位改为qq 
put ‘table_name’,’qy’,’info:company’,’qq’

4.通过timestrap来获取两个版本的数据

# 得到company为tencent的记录get 'table_name','qy',{COLUMN=>'info:company',TIMESTRAP=>1321586238965}# 得到company为qq的数据get 'table_name','qy',{COLUMN=>'info:company',TIMESTRAP=>1321586271843}

5.全表扫描

 scanner规范: 
TIMERANGE, 
FILTER, 
LIMIT, 
STARTROW(start row), 
STOPROW(stop row), 
ROWPREFIXFILTER(row prefix filter,行前缀) 
TIMESTAMP, 
MAXLENGTH, 
or COLUMNS, 
CACHE, 
or RAW, 
VERSIONS

scan 'hbase:meta'scan 'hbase:meta',{COLUMNS => 'info:regioninfo'}scan 'ns1:t1',{COLUMNS=>['c1','c2'],LIMIT=>10,STARTROW=>'xyz'}scan 't1',{COLUMNS=>'c1',TIMERANGE=>[1303668804,1303668904]}scan 't1',{REVERSED=>true}scan 't1',{    ROWPREFIXFILTER=>'row2',    FILTER=>"(QualifierFilter(>=,'binary:xyz'))     AND (TimestampsFilter(123,456))"}scan 't1',{FILTER => org.apache.hadoop.hbase.filter.ColumnPaginationFilter.new(1,0)}scan 't1',{CONSISTENCY=>'TIMELINE'}设置操作属性:scan 't1',{COLUMNS => ['c1','c2'],ATTRIBUTES=>{'mykey'=>'myvalue'}}scan 't1',{COLUMNS=>['c1','c2'],AUTHORIZATIONS=>['PRIVATE','SECRET']}有个额外的选项:CACHE_BLOCKS,默认为true还有个选项:RAW,返回所有cells(包括删除的markers和uncollected deleted cells,不能用来选择特定的columns,默认为default)如:scan 't1',{RAW=>true,VERSIONS=>10}

全表扫描一般不会用,数据量大的时候会死人的。。

6.删除记录

# 删除id为temp的记录的'info:age'字段delete 'member','temp','info:age'# 删除整行deleteall 'member','temp'

7.查询表中有多少行

count 'table_name'or有对表t1的引用tt.count

8.清空表

truncate 'table_name'HBase是先将表disable,再drop the table,最后creating table。

1.3 添加数据

hbase(main):025:0> put 'mydemo','001','base:name','zhangsanfen'

1.4 取值行键为001的数据

hbase(main):021:0> get 'mydemo','001',{COLUMN=>'base'}

1.5 添加一个‘adv’列

hbase(main):023:0> alter 'mydemo',{NAME=>'adv'}

1.6 查询两个列族中的一个列的数据

hbase(main):026:0> get 'mydemo','001',{COLUMN=>['base:name','adv:like']}

1.7 查看表结构:desc 'table'

修改版本号,方便查找3历史记录
hbase(main):034:0> alter 'mydemo',{NAME=>'base',VERSIONS=>3}

1.8 当我们修改了三次name的值,通过以下命令查找历史

hbase(main):043:0> get 'mydemo','001',{COLUMN=>'base:name',VERSIONS=>3}

1.9 get查询一个需要有rowkey(substring:截取)

方法一:(截取:substring)
hbase(main):054:0> get 'mydemo','001',{FILTER=>"ValueFilter(=,'substring:120')"}
方法二:(二进制:binary)
hbase(main):055:0> get 'mydemo','001',{FILTER=>"ValueFilter(=,'binary:zhangsanfeng')"}

2.0 scan 全表查

hbase(main):054:0> scan 'mydemo',FILTER=>"ValueFilter(=,'substring:12')"


5.scan查询

1.限制条件

scan ‘qy’,{COLUMNS=>’name’}

scan ‘qy’,{COLUMNS=>’name:gender’}

scan ‘qy’,{COLUMNS=>[‘name’,’foo’]}

限制查找条数:

scan ‘qy’,{COLUMNS=>[‘name’,’foo’],LIMIT=>2}

限制时间范围:

scan ‘qy’,{ FILTER=>"ValueFilter(=,'substring:120')", TIMERANGE=>[1448045892646,1448045892647]}

QualifierFilter:列过滤器

QualifierFilter对列的名称进行过滤,而不是列的值。

scan ‘qy’,{FILTER=>”PrefixFilter(‘t’) AND QualifierFilter(>=,’binary:b’)”}

TimestampsFilter:时间戳过滤器

scan ‘qy’,{FILTER=>”TimestampsFilter(1448069941270,1548069941230)” }

scan ‘qy’,{FILTER=>”(QualifierFilter(>=,’binary:b’)) AND (TimestampsFilter(1348069941270,1548069941270))” }

ColumnPaginationFilter

scan ‘qy’,{FILTER=>org.apache.hbase.filter.ColumnPaginationFilter.new(2,0)}

cannot load Java class org.apache.hbase.filter.ColumnPaginationFilter

hbase shell应用filter 
1.导入需要的类

import org.apache.hadoop.hbase.filter.CompareFilterimport org.apache.hadoop.hbase.filter.SingleColumnValueFilterimport org.apache.hadoop.hbase.filter.SubstringComparatorimport org.apache.hadoop.hbase.util.Bytes

2.执行命令

scan 'tablename',STARTROW=>'start',COLUMNS=>['family:qualifier'],FILTER=>SingleColumnValueFilter.new(Bytes.toBytes('family'),Bytes.toBytes('qualifier'))

shell执行hbase命令一:

exec hbase_home/bin/hbase shell <<EOF 
status
create 'testtable','colfaml'
list 'testtable'
put 'testtable','myrow-1','colfaml:q1','value-1'
scan 'testtable'
disable 'testtable'
drop 'testtable'
EOF


但是EOF处会自动退出整个脚本,无法执行后面内容,不适用于大的自动化脚本

作者综合hbase官网和一些脚本知识,编写了命令二为可用:

echo "status
create 'testtable','colfaml'
list 'testtable'
put 'testtable','myrow-1','colfaml:q1','value-1'
scan 'testtable'
disable 'testtable'
drop 'testtable'" | hbase_home/bin/hbase shell -n 2>&1
status=$?
echo "The status was " $status
if [ $status == 0 ]; then
    echo "功能测试成功"
else
    echo "功能测试错误"
fi
echo "完毕"


注:2>&1为错误重定向为标准输出1的意思,即命令正确返回0,错误返回1

前面若添加 > /dev/null 即hbase_home/bin/hbase shell -n > /dev/null 2>&1则为将命令输出到只写文件/dev/null,控制台不打印命令输出,且命令正确返回0,错误返回1

这样解决了自动退出问题的同时还能自动判断命令执行情况


 shell批量删除hbase数据

#第一步:通过时间戳找到要删除的数据
#第二步:构建删除数据的shell
#第三步:给delete_all_by_rowkey.sh 加可执行权限  执行删除shell
#!/bin/bash -l
echo '--------------程序从这里开始------------'
#  ${1} ns:table_name
#  ${2} columns
#  ${3} ttl
#  ${4} stop_date
#  ${5} start_time : if ${4} do not input, the start time is defaults to 0;


# hbase(main):002:0> import java.util.Date
# => Java::JavaUtil::Date
# hbase(main):003:0> Date.new(1341304672637).toString()
# => "Tue Jul 03 16:37:52 CST 2012"
# hbase(main):004:0> Date.new(1341301228326).toString()
# => "Tue Jul 03 15:40:28 CST 2012"
# 在shell中,如果e799bee5baa6e4b893e5b19e31333363383464有可读日期,能否转成long类型呢?
# hbase(main):005:0> import java.text.SimpleDateFormat
# => Java::JavaText::SimpleDateFormat
# hbase(main):006:0> import java.text.ParsePosition
# => Java::JavaText::ParsePosition
# hbase(main):015:0> SimpleDateFormat.new("yy/MM/dd").parse("12/07/03",ParsePosition.new(0)).getTime()
# => 1341244800000

table_name=${1}
columns=${2}
ttl=${3}
stop_date=${4}
start_date=0
if [ $# -eq 5 ];then
    start_date=${5}
fi
echo "
   table_name : ${table_name}
   columns : ${columns}
   ttl : ${ttl}
   stop_date : ${stop_date}
   start_date : ${start_date}
"

base_path=$(cd `dirname $0`; pwd)

echo '---------------正在创建缓存文件夹--------------'

mkdir -p ${base_path}/cache_of_delete/${table_name}/
touch ${base_path}/cache_of_delete/${table_name}/rowkey.txt
touch ${base_path}/cache_of_delete/${table_name}/delete_all_by_rowkey.sh

# #######第一步:通过时间戳找到要删除的数据
# 注:这里只有rowkey和其中一列,因为目的是找到rowkey
echo " scan '${table_name}',{COLUMNS=>'${columns}', TIMERANGE=>[${start_date},${stop_date}]}" | hbase shell  | grep 'column' | grep 'timestamp'  |awk '{print $1}' >  ${base_path}/cache_of_delete/${table_name}/rowkey.txt

# ######第二步:构建删除数据的shell
echo '#!/bin/bash -l ' > ${base_path}/cache_of_delete/${table_name}/delete_all_by_rowkey.sh
echo 'exec hbase shell <<EOF ' >> ${base_path}/cache_of_delete/${table_name}/delete_all_by_rowkey.sh

 
cat ${base_path}/cache_of_delete/${table_name}/rowkey.txt|awk '{print "deleteall '\'${table_name}\''", ",", "'\''"$1"'\''"}'  >> ${base_path}/cache_of_delete/${table_name}/delete_all_by_rowkey.sh


echo "EOF " >> ${base_path}/cache_of_delete/${table_name}/delete_all_by_rowkey.sh


# ########第三步:给delete_all_by_rowkey.sh 加可执行权限  执行删除shell
chmod +x ${base_path}/cache_of_delete/${table_name}/delete_all_by_rowkey.sh
#sh ${base_path}/cache_of_delete/${table_name}/delete_all_by_rowkey.sh >> ${base_path}/cache_of_delete/${table_name}/delete.log

#  ##### 第四步: 修改hbase的TTL值
echo '#!/bin/bash -l ' > ${base_path}/cache_of_delete/${table_name}/alter_ttl.sh
echo 'exec hbase shell <<EOF ' >> ${base_path}/cache_of_delete/${table_name}/alter_ttl.sh
echo 'desc '${table_name}' '>> ${base_path}/cache_of_delete/${table_name}/alter_ttl.sh
echo 'disable   '${table_name}' '  >> ${base_path}/cache_of_delete/${table_name}/alter_ttl.sh
echo 'alter '${table_name}', { NAME=>'f',TTL=>'${ttl}'}   '>> ${base_path}/cache_of_delete/${table_name}/alter_ttl.sh
echo 'enable   '${table_name}' '  >> ${base_path}/cache_of_delete/${table_name}/alter_ttl.sh
echo 'desc '${table_name}' '>> ${base_path}/cache_of_delete/${table_name}/alter_ttl.sh
echo "EOF " >> ${base_path}/cache_of_delete/${table_name}/alter_ttl.sh
chmod +x  ${base_path}/cache_of_delete/${table_name}/alter_ttl.sh
#sh ${base_path}/cache_of_delete/${table_name}/alter_ttl.sh

echo '---------------正在删除缓存文件夹--------------'

#rm -rf ${base_path}/cache_of_delete/${table_name}/delete_all_by_rowkey.sh
echo '--------------程序到这里结束------------'

Linux下时间转换的一些命令:

  • date +%s   可以得到UNIX的时间戳;
  • 用shell将日期时间与时间戳互转:

      date -d "2015-08-04 00:00:00" +%s     输出:1438617600

  • 而时间戳转换为字符串可以这样做:

      date -d @1438617600  "+%Y-%m-%d"    输出:2015-08-04  

      date -d @1438617600  "+%Y-%m-%d %H:%M:%S"   2015-08-04 00:00:00"

  • 如果需要得到指定日期的前后几天:
          seconds=`date -d "2015-08-04 00:00:00" +%s`       #得到时间戳
          seconds_new=`expr $seconds + 86400`                   #加上一天的秒数86400
          date_new=`date -d @$seconds_new "+%Y-%m-%d"`   #获得指定日前加上一天的日前

date -d "1970-01-01 UTC 1287331200 seconds" "+%F %T"

date -d @时间戳 "+%Y-%m-%d %H:%M:%S" 

current=“2015-03-11 12:33:41”
echo $current
timeStamp=`date -d "$current" +%s`      #将current转换为时间戳,精确到秒
currentTimeStamp=$((timeStamp*1000+`date "+%N"`/1000000)) #将current转换为时间戳,精确到毫秒
echo $currentTimeStamp

hbase按照时间戳删除记录

1、按照时间戳范围查询记录

echo "scan 'event_log', { COLUMN => 'cf:sid', TIMERANGE => [1466265600272, 1471622400481]} " |  hbase shell > ./record.txt

其中这里的cf:sid和key一致, 时间戳范围需要按照时间自己转换:

#current=`date "+%Y-%m-%d %H:%M:%S"`     #获取当前时间,例:2015-03-11 12:33:41

current=“2015-03-11 12:33:41”
echo $current
timeStamp=`date -d "$current" +%s`      #将current转换为时间戳,精确到秒
currentTimeStamp=$((timeStamp*1000+`date "+%N"`/1000000)) #将current转换为时间戳,精确到毫秒
echo $currentTimeStamp

2、通过shell命令提取record.txt中的sid字段,并拼成hbase删除行命令

cat record.txt|awk '{print "deleteall '\''event_log'\''", ",", "'\''"$1"'\''"}' > del.sh

3、生成hbase删除脚本

在del.sh头尾分别加上:

#!/bin/sh 

exec hbase shell <<EOF 

EOF 

4、执行删除脚本

sh del.sh

hbase的timestamp怎么换算 

hbase shell中timestamp转为可读格式

hbase(main):002:0> import java.util.Date
=> Java::JavaUtil::Date
hbase(main):003:0> Date.new(1341304672637).toString()
=> "Tue Jul 03 16:37:52 CST 2012"
hbase(main):004:0> Date.new(1341301228326).toString()
=> "Tue Jul 03 15:40:28 CST 2012"
####
在shell中,如果有可读日期,能否转成long类型呢?

hbase(main):005:0> import java.text.SimpleDateFormat
=> Java::JavaText::SimpleDateFormat
hbase(main):006:0> import java.text.ParsePosition
=> Java::JavaText::ParsePosition

hbase(main):015:0> SimpleDateFormat.new("yy/MM/dd").parse("12/07/03",ParsePosition.new(0)).getTime()
=> 1341244800000

猜你喜欢

转载自blog.csdn.net/qq_22473611/article/details/106360587