column_families_example.cc 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. #include <cstdio>
  6. #include <string>
  7. #include <vector>
  8. #include "rocksdb/db.h"
  9. #include "rocksdb/slice.h"
  10. #include "rocksdb/options.h"
  11. using namespace ROCKSDB_NAMESPACE;
  12. std::string kDBPath = "/tmp/rocksdb_column_families_example";
  13. int main() {
  14. // open DB
  15. Options options;
  16. options.create_if_missing = true;
  17. DB* db;
  18. Status s = DB::Open(options, kDBPath, &db);
  19. assert(s.ok());
  20. // create column family
  21. ColumnFamilyHandle* cf;
  22. s = db->CreateColumnFamily(ColumnFamilyOptions(), "new_cf", &cf);
  23. assert(s.ok());
  24. // close DB
  25. delete cf;
  26. delete db;
  27. // open DB with two column families
  28. std::vector<ColumnFamilyDescriptor> column_families;
  29. // have to open default column family
  30. column_families.push_back(ColumnFamilyDescriptor(
  31. kDefaultColumnFamilyName, ColumnFamilyOptions()));
  32. // open the new one, too
  33. column_families.push_back(ColumnFamilyDescriptor(
  34. "new_cf", ColumnFamilyOptions()));
  35. std::vector<ColumnFamilyHandle*> handles;
  36. s = DB::Open(DBOptions(), kDBPath, column_families, &handles, &db);
  37. assert(s.ok());
  38. // put and get from non-default column family
  39. s = db->Put(WriteOptions(), handles[1], Slice("key"), Slice("value"));
  40. assert(s.ok());
  41. std::string value;
  42. s = db->Get(ReadOptions(), handles[1], Slice("key"), &value);
  43. assert(s.ok());
  44. // atomic write
  45. WriteBatch batch;
  46. batch.Put(handles[0], Slice("key2"), Slice("value2"));
  47. batch.Put(handles[1], Slice("key3"), Slice("value3"));
  48. batch.Delete(handles[0], Slice("key"));
  49. s = db->Write(WriteOptions(), &batch);
  50. assert(s.ok());
  51. // drop column family
  52. s = db->DropColumnFamily(handles[1]);
  53. assert(s.ok());
  54. // close db
  55. for (auto handle : handles) {
  56. delete handle;
  57. }
  58. delete db;
  59. return 0;
  60. }