如何使用Java客户端在rocksdb中引用和获取特定的列族?

时间:2018-09-25 18:40:16

标签: java rocksdb

考虑以下代码

    try (final ColumnFamilyOptions cfOpts = new ColumnFamilyOptions().optimizeUniversalStyleCompaction()) {
        final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
                new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY, cfOpts),
                new ColumnFamilyDescriptor("my-first-columnfamily".getBytes(), cfOpts)
        );

        final List<ColumnFamilyHandle> columnFamilyHandleList =
                new ArrayList<>();

        try (final DBOptions options = new DBOptions()
                .setCreateIfMissing(true)
                .setCreateMissingColumnFamilies(true);
             final RocksDB db = RocksDB.open(options,
                     "/mnt/my_db", cfDescriptors,
                     columnFamilyHandleList)) {
            try {
                // Question: How do I refer to a particular column family by name, for example my-first-columnfamily
                db.put(columnFamilyHandleList.get(0), "myKey".getBytes(), "myValue".getBytes());

            } finally {
                for (final ColumnFamilyHandle columnFamilyHandle :
                        columnFamilyHandleList) {
                    columnFamilyHandle.close();
                }
            }
        } catch(Exception e) {

        }
    }
}

在下一行

db.put(columnFamilyHandleList.get(0), "myKey".getBytes(), "myValue".getBytes());

我希望put能够选择column familyput中的哪个,但是put需要一个ColumnFamilyHandle,而ColumnFamilyHandle却不能包含描述符名称,因此很难选择放置目标。

有人可以指出实现上述目标的方向吗?

谢谢

1 个答案:

答案 0 :(得分:0)

ColumnFamilyHandle具有getName方法,请参见here

因此,您可以创建一个辅助方法,该方法在列族句柄列表中搜索名称。

 public ColumnFamilyHandle getColumnFamilyHandle(byte[] name) {
    return columnFamilyHandles
        .stream()
        .filter(
            handle -> {
              try {
                return Arrays.equals(handle.getName(), name);
              } catch (Exception ex) {
                throw new RuntimeException(ex);
              }
            })
        .findAny()
        .orElse(null);
  }