1 // Copyright (c) 2011-present, Facebook, Inc. All rights reserved. 2 // This source code is licensed under both the GPLv2 (found in the 3 // COPYING file in the root directory) and Apache 2.0 License 4 // (found in the LICENSE.Apache file in the root directory). 5 6 import org.rocksdb.*; 7 8 import java.util.ArrayList; 9 import java.util.List; 10 11 public class RocksDBColumnFamilySample { 12 static { RocksDB.loadLibrary()13 RocksDB.loadLibrary(); 14 } 15 main(final String[] args)16 public static void main(final String[] args) throws RocksDBException { 17 if (args.length < 1) { 18 System.out.println( 19 "usage: RocksDBColumnFamilySample db_path"); 20 System.exit(-1); 21 } 22 23 final String db_path = args[0]; 24 25 System.out.println("RocksDBColumnFamilySample"); 26 try(final Options options = new Options().setCreateIfMissing(true); 27 final RocksDB db = RocksDB.open(options, db_path)) { 28 29 assert(db != null); 30 31 // create column family 32 try(final ColumnFamilyHandle columnFamilyHandle = db.createColumnFamily( 33 new ColumnFamilyDescriptor("new_cf".getBytes(), 34 new ColumnFamilyOptions()))) { 35 assert (columnFamilyHandle != null); 36 } 37 } 38 39 // open DB with two column families 40 final List<ColumnFamilyDescriptor> columnFamilyDescriptors = 41 new ArrayList<>(); 42 // have to open default column family 43 columnFamilyDescriptors.add(new ColumnFamilyDescriptor( 44 RocksDB.DEFAULT_COLUMN_FAMILY, new ColumnFamilyOptions())); 45 // open the new one, too 46 columnFamilyDescriptors.add(new ColumnFamilyDescriptor( 47 "new_cf".getBytes(), new ColumnFamilyOptions())); 48 final List<ColumnFamilyHandle> columnFamilyHandles = new ArrayList<>(); 49 try(final DBOptions options = new DBOptions(); 50 final RocksDB db = RocksDB.open(options, db_path, 51 columnFamilyDescriptors, columnFamilyHandles)) { 52 assert(db != null); 53 54 try { 55 // put and get from non-default column family 56 db.put(columnFamilyHandles.get(0), new WriteOptions(), 57 "key".getBytes(), "value".getBytes()); 58 59 // atomic write 60 try (final WriteBatch wb = new WriteBatch()) { 61 wb.put(columnFamilyHandles.get(0), "key2".getBytes(), 62 "value2".getBytes()); 63 wb.put(columnFamilyHandles.get(1), "key3".getBytes(), 64 "value3".getBytes()); 65 wb.remove(columnFamilyHandles.get(0), "key".getBytes()); 66 db.write(new WriteOptions(), wb); 67 } 68 69 // drop column family 70 db.dropColumnFamily(columnFamilyHandles.get(1)); 71 } finally { 72 for (final ColumnFamilyHandle handle : columnFamilyHandles) { 73 handle.close(); 74 } 75 } 76 } 77 } 78 } 79