How to handle multiple values for the same key
mainLMDB supports duplicate keys if the database is configured with the DatabaseOpenFlags.DuplicatesSort flag.
To retrieve these values, you can use a Cursor:
- Create a cursor with
tx.CreateCursor(db). - Position it at the first occurrence using
cursor.Set(key). - Iterate through duplicates using
cursor.NextDuplicate()until it returns aresultCodeother thanMDBResultCode.Success.
Alternatively, you can use the convenience method cursor.AllValues(key) to get an IEnumerable of all values associated with that key.
// Configure the database to support duplicate keys
var dbConfig = new DatabaseConfiguration { Flags = DatabaseOpenFlags.Create | DatabaseOpenFlags.DuplicatesSort };
// ... inside a transaction ...
using (var db = tx.OpenDatabase(configuration: dbConfig))
{
var key = Encoding.UTF8.GetBytes("fruit");
tx.Put(db, key, Encoding.UTF8.GetBytes("apple"));
tx.Put(db, key, Encoding.UTF8.GetBytes("cherry"));
tx.Commit();
}
// ... retrieval using cursor ...
using (var cursor = tx.CreateCursor(db))
{
var result = cursor.Set(key);
if(result == MDBResultCode.Success)
{
do
{
var current = cursor.GetCurrent();
Console.WriteLine($"{Encoding.UTF8.GetString(current.key.AsSpan())}: {Encoding.UTF8.GetString(current.value.AsSpan())}");
}
while (cursor.NextDuplicate().resultCode == MDBResultCode.Success);
}
// Or simpler:
var values = cursor.AllValues(key);
foreach(var value in values)
{
Console.WriteLine($"fruit: {Encoding.UTF8.GetString(value.AsSpan())}");
}
}