我想通过以下Scala代码访问lmdb中的密钥:
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()
输出为:
HelloWorld
为什么在输出中看不到greeting
!
对如何访问密钥有任何想法吗?
答案 0 :(得分:1)
就像在每个地图实现中一样,要访问键,您需要对其进行迭代:
try (CursorIterator<ByteBuffer> it = db.iterate(txn, KeyRange.all())) {
for (final KeyVal<ByteBuffer> kv : it.iterable()) {
println(UTF_8.decode(kv.key()).toString())
}
}
您可以在代码示例here
中看到更多示例