Pacific-Design.com

    
Home Index

1. Redis

2. HashMap

Redis / HashMap /

Redis can append new HashMaps into existing HashMaps already in value

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import redis.clients.jedis.Jedis
import java.io.{ByteArrayOutputStream, ObjectOutputStream}
import java.util
import scala.io.Source

/**
    * HMSET - appends existing HashMap in Redis Key/Value with new HashMap
    * Returns: { hash_key_4=hash_value_4, hash_key_3=hash_value_3, hash_key_2=hash_value_2,
    * hash_key_1=hash_value_1, hash_key_6=hash_value_6, hash_key_5=hash_value_5 }
    */
  def insert_hmset(): Unit = {

    val jedis = new Jedis("localhost")

    val map1: util.HashMap[String, String] = new java.util.HashMap[String, String]
    map1.put("hash_key_1", "hash_value_1")
    map1.put("hash_key_2", "hash_value_2")
    map1.put("hash_key_3", "hash_value_3")
    jedis.hmset("redis_key", map1)

    val map2: util.HashMap[String, String] = new java.util.HashMap[String, String]
    map2.put("hash_key_4", "hash_value_4")
    map2.put("hash_key_5", "hash_value_5")
    map2.put("hash_key_6", "hash_value_6")
    jedis.hmset("redis_key", map2)

    println(jedis.hgetAll("redis_key"))
    println(jedis.hgetAll("redis_key").get("hash_key_5"))

    val res = jedis.hgetAll("redis_key")
    println("HGETALL = " + res.get("hash_key_3"))

    // get a single value
    println("HMSET = " + jedis.hmget("redis_key", "hash_key_1"))
    println("HMSET = " + jedis.hmget("redis_key", "hash_key_3"))
    println("HMSET = " + jedis.hmget("redis_key", "hash_key_4"))
    println("HMSET = " + jedis.hmget("redis_key", "hash_key_6"))

  }

  /**
    * HGETALL - throw exception when non-existent key is accessed
    */
  def get_non_existed_key(): Unit = {

    val jedis = new Jedis("localhost")

    try {
      val result3 = jedis.hgetAll("key")
      println("HGETALL = " + result3)
    } catch {
      case _: Throwable => {
        println("Key Does not exist")
      }
    }

  }