Search code examples
servicestackpocodynamo

How to batch get items using servicestack.aws PocoDynamo?


With Amazon native .net lib, batchget is like this

var batch = context.CreateBatch<MyClass>();
batch.AddKey("hashkey1");
batch.AddKey("hashkey2");
batch.AddKey("hashkey3");
batch.Execute();
var result = batch.results;

Now I'm testing to use servicestack.aws, however I couldn't find how to do it. I've tried the following, both failed.

//1st try
var q1 = db.FromQueryIndex<MyClass>(x => x.room_id == "hashkey1" || x.room_id == "hashkey2"||x.room_id == "hashkey3");
var result = db.Query(q1);

//2nd try
var result = db.GetItems<MyClass>(new string[]{"hashkey1","hashkey2","hashkey3"});

In both cases, it threw an exception that says Additional information: Invalid operator used in KeyConditionExpression: OR

Please help me. Thanks!


Solution

  • Using GetItems should work as seen with this Live Example on Gistlyn:

    public class MyClass
    {
        public string Id { get; set; }
        public string Content { get; set; }
    }
    
    db.RegisterTable<MyClass>();
    
    db.DeleteTable<MyClass>();  // Delete existing MyClass Table (if any)
    db.InitSchema();         // Creates MyClass DynamoDB Table
    
    var items = 5.Times(i => new MyClass { Id = $"hashkey{i}", Content = $"Content {i}" });
    db.PutItems(items);
    
    var dbItems = db.GetItems<MyClass>(new[]{ "hashkey1","hashkey2","hashkey3" });
    "Saved Items: {0}".Print(dbItems.Dump());
    

    If your Item has both a Hash and a Range Key you'll need to use the GetItems<T>(IEnumerable<DynamoId> ids) API, e.g:

    var dbItems = db.GetItems<MyClass>(new[]{
        new DynamoId("hashkey1","rangekey1"),
        new DynamoId("hashkey2","rangekey3"),
        new DynamoId("hashkey3","rangekey4"),
    });
    

    Query all Items with same HashKey

    If you want to fetch all items with the same HashKey you need to create a DynamoDB Query as seen with this Live Gistlyn Example:

    var items = 5.Times(i => new MyClass { 
        Id = $"hashkey{i%2}", RangeKey = $"rangekey{i}", Content = $"Content {i}" });
    db.PutItems(items);
    
    var rows = db.FromQuery<MyClass>(x => x.Id == "hashkey1").Exec().ToArray();
    rows.PrintDump();