在 LMDB 中检索密钥
Retrieve keys in LMDB
我想从 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
!!
知道如何访问密钥吗?
就像在每个地图实现中一样,为了访问键,您需要迭代它们:
try (CursorIterator<ByteBuffer> it = db.iterate(txn, KeyRange.all())) {
for (final KeyVal<ByteBuffer> kv : it.iterable()) {
println(UTF_8.decode(kv.key()).toString())
}
}
您可以在代码示例中查看更多示例here
我想从 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
!!
知道如何访问密钥吗?
就像在每个地图实现中一样,为了访问键,您需要迭代它们:
try (CursorIterator<ByteBuffer> it = db.iterate(txn, KeyRange.all())) {
for (final KeyVal<ByteBuffer> kv : it.iterable()) {
println(UTF_8.decode(kv.key()).toString())
}
}
您可以在代码示例中查看更多示例here