DEV Community

Simer Plaha
Simer Plaha

Posted on • Edited on

Intro to SwayDB

SwayDB is an embeddable persistent and in-memory key-value store/database.

Here I will try to demonstrate on how to create a Map in Scala and play with some basic APIs to do simple CRUD operations.

Creating a Map

You can ignore Nothing and Bag.Less for now which will explained in future posts.

import swaydb._ //swaydb's APIs import swaydb.serializers.Default._ //default serialisers val map = memory.Map[Int, String, Nothing, Bag.Less]().get //create a memory map 
Enter fullscreen mode Exit fullscreen mode

Similarly a persistent Map can be created by replacing memory.Map with persistent.Map and providing a folder name.

val map = persistent.Map[Int, String, Nothing, Bag.Less](dir = "target/myMap").get 
Enter fullscreen mode Exit fullscreen mode

Basic Put & Get

 map.put(key = 1, value = "one") map.get(key = 1) //returns Some("one") 
Enter fullscreen mode Exit fullscreen mode

Expiring & Updating data

//put and expire after 1 hour map.put(key = 2, value = "two", expireAfter = 1.hour) //updates value but leave the expiration unchanged. map.update(key = 2, value = "two updated") //returns expiration deadline. map.expiration(key = 2) 
Enter fullscreen mode Exit fullscreen mode

Remove/Deleting data

Batch removes both keys.

map.remove(keys = Seq(1, 2)) //return true - Map is now empty. map.isEmpty 
Enter fullscreen mode Exit fullscreen mode

Run on Scastie.

Done!

Top comments (0)