简体   繁体   English

LMDB Java使用相同的键检索所​​有值

[英]LMDB Java retrieve all values with same key

I want to store multiple values with the same key. 我想用相同的键存储多个值。 I made sure to include the MDB_DUPSORT flag when creating the database. 在创建数据库时,我确保包括MDB_DUPSORT标志。 I am also aware this limits the value size but in this specific case this is not a problem. 我也知道这限制了值的大小,但是在这种特定情况下,这不是问题。

My problem starts when I want to read the values with the same keys. 当我想使用相同的键读取值时,我的问题就开始了。 I searched but could not find a clear answer on how to do this. 我进行了搜索,但找不到关于如何执行此操作的明确答案。

So basically: how to retrieve all values with the same key? 所以基本上:如何使用相同的键检索所​​有值?

I use lmdbjava to read/write from the database. 我使用lmdbjava从数据库读取/写入。

I tried this but the iterator continues on with the next key and does not stop when the last value is read: 我试过了,但是迭代器继续使用下一个键,并且在读取最后一个值时不会停止:

try(Txn<ByteBuffer> txn = env.txnRead()) {
    CursorIterator<ByteBuffer> cursor = db.iterate(txn, KeyRange.atLeast(key));

    for(CursorIterator.KeyVal<ByteBuffer> kv : cursor.iterable()) {
        ByteBuffer value = kv.val();

        byte[] bytes = new byte[value.remaining()];

        value.get(bytes);

        System.out.println(bytes);
    }
}

Rather than KeyRange.atLeast which according to the javadoc 而不是根据Javadoc的KeyRange.atLeast

starts on the passed key (or the first key immediately after it) and iterate forward until no keys remain 从传递的键(或紧随其后的第一个键)开始,并向前迭代,直到没有剩余键为止

I think you'd want to use KeyRange.closed 我认为您想使用KeyRange.closed

Iterate forward between the passed keys, matching on the first keys directly equal to the passed key (or immediately following it in the case of the "start" key, or immediately preceding it in the case of the "stop" key). 在传递的键之间向前迭代,在与传递的键直接相等的第一个键上进行匹配(如果是“开始”键,则紧随其后;如果是“停止”键,则紧随其后)。

Test for it 测试一下

  @Test
  public void dupSortKeyRange() {

    final Dbi<ByteBuffer> db = env.openDbi(DB_1, MDB_CREATE, MDB_DUPSORT);

    try (Txn<ByteBuffer> txn = env.txnWrite()) {
      db.put(txn, bb(5), bb(6));
      db.put(txn, bb(5), bb(7));
      db.put(txn, bb(5), bb(8));
      db.put(txn, bb(6), bb(9));
      txn.commit();
    }

    try (Txn<ByteBuffer> txn = env.txnRead()) {
      ByteBuffer key = bb(5);

      List<Integer> keyValues = new ArrayList<>();
      CursorIterator<ByteBuffer> cursor = db.iterate(txn, KeyRange.closed(key, key));
      for (CursorIterator.KeyVal<ByteBuffer> kv : cursor.iterable()) {
        ByteBuffer value = kv.val().get(new byte[kv.val().remaining()]);
        keyValues.add(value.getInt(0));
      }

      assertEquals(3, keyValues.size(), 0);
      assertTrue(keyValues.containsAll(Arrays.asList(6, 7, 8)));
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM