Search code examples
xodus

Nested Cursors over two different Stores


I have following code:

...

Transaction xodusTransaction = xodusEnvironment.beginReadonlyTransaction();

Store leftStore = xodusEnvironment.openStore(leftName, StoreConfig.USE_EXISTING, xodusTransaction, false);

Store rightStore = xodusEnvironment.openStore(rightName, StoreConfig.USE_EXISTING, xodusTransaction, false);

try(Cursor leftCursor = leftStore.openCursor(xodusTransaction);
Cursor rightCursor = rightStore.openCursor(xodusTransaction)) {

  while(leftCursor.getNext()) {
    while(rightCursor.getNext()) {
    // Do actual work with data from both stores
    }
  }
}
... 

I expect that internal loop will be fired N*M times, where N - cardinality of leftStore and M - cardinality of rightStore.

On practice external loop fires only once and internal loop fires M-times.

If I rewrite the code in following way (flattering nested loops):

...
while(leftCursor.getNext()) {
 ...
}

while(rightCursor.getNext()) {
 ...
}

...

Then both loops fires as expected N-times for leftStore and M-times for rightStore.

The question is: is it possible to make nested cursor traveling? If yes, kindly please guide me.

Thank you!

-Taras


Solution

  • Once cursor.getNext() returned false (there is no next key/value pair), it will never return true for this Cursor instance. To traverse a Store again, reopen cursor.

    Here is the code traversing two Stores as a matrix, i.e. all pairwise combinations of key/value pairs from both Stores:

    try (Cursor leftCursor = leftStore.openCursor(txn)) {
        while (leftCursor.getNext()) {
            try (Cursor rightCursor = rightStore.openCursor(txn)) {
                while (rightCursor.getNext()) {
                    // Do actual work with data from both stores
                }
            }
        }
    }