Phoenix简介及安装
1、Phoenix简介
定义
:通过Phoenix可以使用标准JDBC API代替HBase客户端API来创建表,插入数据和查询HBase数据。
特点
:
- 容易集成:如Spark,Hive,Pig,Flume和Map Reduce
- 操作简单:DML命令以及通过DDL命令创建和操作表和版本化增量更改
- 支持HBase二级索引创建
2、安装
-
解压安装包至指定目录
tar -zxvf apache-phoenix-5.0.0-HBase-2.0-bin.tar.gz -C /opt/module/ mv apache-phoenix-5.0.0-HBase-2.0-bin phoenix-5.0.0
-
复制server包并分发到各个节点的hbase/lib
cp /opt/module/phoenix-5.0.0/phoenix-5.0.0-HBase-2.0-server.jar /opt/module/hbase/lib/ xsync /opt/module/hbase/lib/phoenix-5.0.0-HBase-2.0-server.jar
-
配置环境变量并source
#phoenix export PHOENIX_HOME=/opt/module/phoenix-5.0.0 export PHOENIX_CLASSPATH=$PHOENIX_HOME export PATH=$PATH:$PHOENIX_HOME/bin
-
重启HBase
-
连接Phoenix
/opt/module/phoenix/bin/sqlline.py hadoop102,hadoop103,hadoop104:2181
3、Phoenix Shell命令
-
查
!table / !tables
-
查数据
select * from student; select * from student where id='1001';
-
创建表
--直接指定单个列作为RowKey CREATE TABLE IF NOT EXISTS student( id VARCHAR primary key, name VARCHAR, addr VARCHAR); --指定多个列的联合作为RowKey CREATE TABLE IF NOT EXISTS us_population ( State CHAR(2) NOT NULL, City VARCHAR NOT NULL, Population BIGINT CONSTRAINT my_pk PRIMARY KEY (state, city));
在phoenix中,表名等会自动转换为大写,若要小写,使用双引号,如"us_population"。
Phoenix中建表,会在HBase中创建一张对应的表。为了减少数据对磁盘空间的占用,Phoenix默认会对HBase中的列名做编码处理。具体规则可参考官网链接:https://phoenix.apache.org/columnencoding.html,若不想对列名编码,可在建表语句末尾加上COLUMN_ENCODED_BYTES = 0;
-
插入数据
upsert into student values('1001','zhangsan','beijing')
-
删除记录
delete from student where id='1001'
-
删除表
drop table student;
-
退出
!quit
4、表的映射
默认情况下, HBase中已存在的表,通过Phoenix是不可见的。如果要在Phoenix中操作HBase中已存在的表,可以在Phoenix中进行表的映射。映射方式有两种:视图映射和表映射。
测试
表test
Rowkey | info1 | info2 |
---|---|---|
id | name | address |
-
在hbase shell中创建表test
hbase(main):011:0> create 'test','info1','info2'
-
进入Phoenix客户端
sqlline.py !table
此时,在phoenix客户端中不能查找到test表
-
视图映射:Phoenix创建的视图是只读的,所以只能用来做查询,无法通过视图对数据进行修改等操作。
create view "test"(id varchar primary key,"info1"."name" varchar, "info2"."address" varchar);
删除视图
drop view "test";
-
表映射:在Pheonix创建表去映射HBase中已经存在的表,是可以修改删除HBase中已经存在的数据的。而且,删除Phoenix中的表,那么HBase中被映射的表也会被删除。
进行表映射时,不能使用列名编码,需将column_encoded_bytes设为0
create table "test"(id varchar primary key,"info1"."name" varchar, "info2"."address" varchar) column_encoded_bytes=0;
存在的一些问题
HBase中的数字,底层存储为补码,而Phoenix中的数字,底层存储为在补码的基础上,将符号位反转。故当在Phoenix中建表去映射HBase中已存在的表,当HBase中有数字类型的字段时,会出现解析错误的现象。
--Hbase演示:
create 'test_number','info'
put 'test_number','1001','info:number',Bytes.toBytes(1000)
scan 'test_number',{COLUMNS => 'info:number:toLong'}
--phoenix演示:
create view "test_number"(id varchar primary key,"info"."number" bigint);
select * from "test_number";
解决方案:
-
Phoenix种提供了unsigned_int,unsigned_long等无符号类型,其对数字的编码解码方式和HBase是相同的,如果无需考虑负数,那在Phoenix中建表时采用无符号类型。
--phoenix演示: drop view "test_number"; create view "test_number"(id varchar primary key,"info"."number" unsigned_long); select * from "test_number";
-
如需考虑负数的情况,则可通过Phoenix自定义函数,将数字类型的最高位,即符号位反转即可,自定义函数可参考如下链接:https://phoenix.apache.org/udf.html。