// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.IO; using System.Text; using RocksDbSharp; namespace R { public class Data { public int Iv { get; set; } public double Xv { get; set; } public string Sv { get; set; } public override string ToString() { return string.Format("(iv: {0}, xv: {1}, sv: {2})", Iv, Xv, Sv); } } public class Program { private static byte[] Prep(string key) { return Encoding.UTF8.GetBytes(key); } private static byte[] Serialize(Data d) { MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); bw.Write(d.Iv); bw.Write(d.Xv); bw.Write((short)d.Sv.Length); bw.Write(Encoding.UTF8.GetBytes(d.Sv)); bw.Flush(); return ms.ToArray(); } private static Data Deserialize(byte[] b) { MemoryStream ms = new MemoryStream(b); BinaryReader br = new BinaryReader(ms); Data d = new Data(); d.Iv = br.ReadInt32(); d.Xv = br.ReadDouble(); int len = br.ReadInt16(); byte[] temp = new byte[len]; br.Read(temp, 0, temp.Length); d.Sv = Encoding.UTF8.GetString(temp); return d; } private static void Dump(RocksDb db, string key) { Console.WriteLine("Key={0}", key); byte[] rawvalue = db.Get(Prep(key)); if(rawvalue != null) { Data value = Deserialize(rawvalue); Console.WriteLine(value); } else { Console.WriteLine("Not found"); } } private const int NREC = 1000; private const int DN_OFFSET = 3 * NREC; public static void Main(string[] args) { using (RocksDb db = RocksDb.Open(new DbOptions().SetCreateIfMissing(true), "/work/R/DB")) { // put data for (int i = 0; i < NREC; i++) { string putkey = "Key#" + (DN_OFFSET + i + 1); Data value = new Data { Iv = i + 1, Xv = i + 1.0, Sv = string.Format("This is value {0}", i + 1) }; db.Put(Prep(putkey), Serialize(value)); } // string key; key = "Key#" + (DN_OFFSET + 77); // get Dump(db, key); // delete db.Remove(Prep(key)); // get non existing Dump(db, key); // key = "Key#" + (DN_OFFSET + 88); // update and get Dump(db, key); Data updvalue = (Data)Deserialize(db.Get(Prep(key))); updvalue.Iv = updvalue.Iv + 1; updvalue.Xv = updvalue.Xv + 0.1; updvalue.Sv = updvalue.Sv + " updated"; db.Put(Prep(key), Serialize(updvalue)); Dump(db, key); // list all using (Iterator it = db.NewIterator()) { it.SeekToFirst(); int n = 0; while (it.Valid()) { string itkey = Encoding.UTF8.GetString(it.Key()); if(!itkey.StartsWith("Key#")) { Console.WriteLine("Unexpected key: " + itkey); } Data itvalue = (Data)Deserialize(db.Get(Prep(itkey))); if (itvalue.Iv < 1 || NREC < itvalue.Iv) { Console.WriteLine("Unexpected value :" + itvalue); } n++; it.Next(); } Console.WriteLine(n); } // list keys where "Key#75" <= key < "Key#85" using (Iterator it2 = db.NewIterator()) { it2.Seek(Prep("Key#" + (DN_OFFSET + 75))); int n2 = 0; while (it2.Valid()) { string it2key = Encoding.UTF8.GetString(it2.Key()); if(string.Compare(it2key, "Key#" + (DN_OFFSET + 85)) >= 0) break; n2++; it2.Next(); } Console.WriteLine(n2); } } } } }