面试题答案
一键面试单行数据插入
在HBase Shell环境下,使用 put
命令插入单行数据。
语法格式为:put '<table name>', '<row key>', '<column family:column qualifier>', '<value>', <timestamp>
。其中,<timestamp>
为可选参数,如果不指定,系统会自动使用当前时间戳。
例如,假设有一个名为 students
的表,有 info
列族,要插入一条学生数据:
put'students', '1001', 'info:name', 'Alice'
put'students', '1001', 'info:age', '20'
这里,表名是 students
,行键 1001
代表一个学生的唯一标识,info:name
是列族 info
下的 name
列限定符,值为 Alice
,同理插入了年龄信息。
批量插入数据
- 使用循环
可以在HBase Shell中使用Ruby的循环结构来实现批量插入。
例如,要向
students
表批量插入10条学生数据:
上述代码使用1.upto(10) do |i| row_key = "student_#{i}" put'students', row_key, 'info:name', "Student_#{i}" put'students', row_key, 'info:age', (18 + i).to_s end
1.upto(10)
循环,每次生成一个新的行键student_i
,并为每个学生插入姓名和年龄信息。 - 使用脚本文件
可以编写一个包含多个
put
命令的脚本文件,例如batch_insert.hbase
:
然后在HBase Shell中通过put'students','student_11', 'info:name', 'Bob' put'students','student_11', 'info:age', '22' put'students','student_12', 'info:name', 'Charlie' put'students','student_12', 'info:age', '23'
source
命令执行该脚本:
这样就可以批量插入脚本中指定的数据。hbase(main):001:0> source 'batch_insert.hbase'