I wanted to access the key in lmdb from scala code as below:
val file = new File("test.txt")
val createEnv = create().setMapSize(10485760).setMaxDbs(1)
val env = createEnv.open(file,MDB_NOSUBDIR)
val db = env.openDbi(LMDBMain.DB_NAME, MDB_CREATE)
//define key ,val pair
val key = allocateDirect(env.getMaxKeySize)
val value = allocateDirect(700)
//insert to db
key.put("Greeting".getBytes(UTF_8)).flip
value.put("Hello World".getBytes(UTF_8)).flip
db.put(key, value)
//fetching data
val txn = env.txnRead
try {
val fetchedKey : ByteBuffer = db.get(txn,key)
val fetchedVal : ByteBuffer = txn.`val`()
println(UTF_8.decode(fetchedVal).toString())
println(UTF_8.decode(fetchedKey).toString())
txn.commit()
} finally if (txn != null) txn.close()
the output is :
HelloWorld
why I can't see greeting
in my output !!
any idea to how I can access key ?
Like in every map implementation, for accessing the keys, you need to iterate them:
try (CursorIterator<ByteBuffer> it = db.iterate(txn, KeyRange.all())) {
for (final KeyVal<ByteBuffer> kv : it.iterable()) {
println(UTF_8.decode(kv.key()).toString())
}
}
You can see more examples in the code examples here