-
-
Save KrzysFR/86c01933f2cdf1023622 to your computer and use it in GitHub Desktop.
Updated to use directories, encoders, retry loops, ...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static async Task Demo() | |
{ | |
var cancellationTokenSource = new CancellationTokenSource(); | |
using (var db = await Fdb.OpenAsync()) | |
{ | |
// open the "my_app/my_data" folder (created if missing) | |
var folder = await db.Directory.CreateOrOpenAsync(new [] { "my_app", "my_data" }, cancellationTokenSource.Token); | |
var firstId = Guid.NewGuid(); | |
var firstSequence = new[] { "foo", "bar", "baz" }; | |
// create a composite key encoder and merge it with the subspace | |
// => encodes keys and append the correct prefix in a single step! | |
var location = new FdbEncoderSubspace<Guid, int>( | |
folder, | |
KeyValueEncoders.Tuples.CompositeKey<Guid, int>() | |
); | |
// create a value encoder that encodes UTF-8 strings | |
// => could use any encoding scheme, including json or tuples, doesn't really matter. | |
var encoder = KeyValueEncoders.Values.StringEncoder; | |
// writing the data: | |
await db.WriteAsync((trans) => | |
{ | |
var version = 0; | |
foreach (var item in firstSequence) | |
{ | |
trans.Set( | |
location.EncodeKey(firstId, ++version), | |
encoder.EncodeValue(item) | |
); | |
} | |
}, cancellationTokenSource.Token); | |
// get all items for a sequence: | |
var items = await db.QueryAsync( | |
(trans) => trans | |
.GetRange(FdbKeyRange.StartsWith(location.Partial.EncodeKey(firstId))) | |
.Select(kv => encoder.DecodeValue(kv.Value)), | |
cancellationTokenSource.Token | |
); | |
foreach(var item in items) Console.WriteLine(item); | |
// output: foo, bar, baz | |
// get all items starting with the third: | |
items = await db.QueryAsync( | |
(trans) => trans | |
.GetRange(FdbKeyRange.StartsWith(location.Partial.EncodeKey(firstId))) | |
.Skip(2) // ok with small offsets ! | |
.Select(kv => encoder.DecodeValue(kv.Value)), | |
cancellationTokenSource.Token | |
); | |
foreach (var item in items) Console.WriteLine(item); | |
// output: baz | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment