hbase - 在HBase中,如何存储列表或数组结构

标签 hbase

我有一些数据,看起来像这样:

{'a-name':['v1','v2','v3'...]}

现在,我将存储到HBase,列名称为a-name,如何存储值(['v1','v2','v3'...])?

最佳答案

HBase中的值存储为一组字节,这意味着数组的序列化和反序列化是应用程序的责任。您可以使用Writables(请参见下面的示例)或使用Avro / Thrift / JSON / etc手动进行操作。序列化-反序列化您的数据

以下是如何执行此操作的示例:

public class test {
    public static Writable toWritable(ArrayList<String> list) {
        Writable[] content = new Writable[list.size()];
        for (int i = 0; i < content.length; i++) {
            content[i] = new Text(list.get(i));
        }
        return new ArrayWritable(Text.class, content);
    }
    public static ArrayList<String> fromWritable(ArrayWritable writable) {
        Writable[] writables = ((ArrayWritable) writable).get();
        ArrayList<String> list = new ArrayList<String>(writables.length);
        for (Writable wrt : writables) {
            list.add(((Text)wrt).toString());
        }
        return list;
    }
    public static void main (String[] args) throws IOException {
        ArrayList<String> arr = Lists.newArrayList("a", "b", "c");
        HTable table = new HTable(HBaseConfiguration.create(), "t1");
        Put p = new Put(Bytes.toBytes("key1"));
        p.add(Bytes.toBytes("f1"), Bytes.toBytes("a"), WritableUtils.toByteArray(toWritable(arr)));
        table.put(p);
        Get g = new Get(Bytes.toBytes("key1"));
        Result r = table.get(g);
        ArrayWritable w = new ArrayWritable(Text.class);
        w.readFields(
                new DataInputStream(
                        new ByteArrayInputStream(
                                r.getValue(Bytes.toBytes("f1"), Bytes.toBytes("a"))
                        )
                )
        );
        ArrayList<String> arr2 = fromWritable(w);
        System.out.println(arr2.toString());
    }
}


以下是一些用于将不同类型序列化/反序列化为可写内容的通用代码:https://github.com/elasticsearch/elasticsearch-hadoop/blob/master/mr/src/main/java/org/elasticsearch/hadoop/util/WritableUtils.java

关于hbase - 在HBase中,如何存储列表或数组结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26817107/

相关文章:

java - 如何使用来自不同网络的 Java 库(org.apache.hadoop.hbase.client)连接 Hbase?

.net - 用于 .Net 应用程序的实时数据库(例如 HBase)

HBase:扫描列限定符 - 这可能吗?

hbase - 使用 HBase 进行行分页

apache - HBase模式设计示例

hbase - 在不禁用 HBASE 表的情况下更改表结构的含义

hadoop - Apache Drill 查询 HBase 表

unix - HBASE_HOME为空,并导致 “Could not locate executable null\bin\winutils.exe in the Hadoop binaries”错误

hadoop - 有什么方法可以创建自动缩放的 Hadoop Hbase 集群

java - hbase importTsv FileNotFoundException