github.com/flower-corp/rosedb@v1.1.2-0.20230117132829-21dc4f7b319a/examples/hash/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"path/filepath"
     6  
     7  	"github.com/flower-corp/rosedb"
     8  )
     9  
    10  func main() {
    11  	path := filepath.Join("/tmp", "rosedb")
    12  	opts := rosedb.DefaultOptions(path)
    13  	db, err := rosedb.Open(opts)
    14  	if err != nil {
    15  		fmt.Printf("open rosedb err: %v", err)
    16  		return
    17  	}
    18  
    19  	err = db.HSet([]byte("watermelon"), []byte("hash"), []byte("In summer, I love watermelon."))
    20  	if err != nil {
    21  		fmt.Printf("HSet error: %v", err)
    22  	}
    23  
    24  	value, err := db.HGet([]byte("watermelon"), []byte("hash"))
    25  	if err != nil {
    26  		fmt.Printf("HGet error: %v", err)
    27  	}
    28  	fmt.Println(string(value))
    29  
    30  	exist, err := db.HExists([]byte("watermelon"), []byte("hash"))
    31  	if err != nil {
    32  		fmt.Printf("HExists error: %v", err)
    33  	}
    34  	if exist {
    35  		fmt.Println("Hash key watermelon exist.")
    36  	}
    37  
    38  	fields, err := db.HKeys([]byte("watermelon"))
    39  	if err != nil {
    40  		fmt.Printf("Hkeys error: %v", err)
    41  	}
    42  	fmt.Println("The fields in watermelon are:", fields)
    43  
    44  	ok, err := db.HSetNX([]byte("key-1"), []byte("field-1"), []byte("value-1"))
    45  	if err != nil {
    46  		fmt.Printf("HSetNx error: %v", err)
    47  	}
    48  	fmt.Println(ok)
    49  
    50  	value, err = db.HGet([]byte("key-1"), []byte("field-1"))
    51  	if err != nil {
    52  		fmt.Printf("Error when key-1/field-1 is trying to get: %v", err)
    53  	}
    54  	fmt.Printf("key-1/value-1: %s", string(value))
    55  
    56  	_ = db.HSet([]byte("my_hash"), []byte("f1"), []byte("val-1"), []byte("f2"), []byte("val-2"))
    57  	values, err := db.HMGet([]byte("my_hash"), []byte("f1"), []byte("f2"))
    58  	if err != nil {
    59  		fmt.Printf("hmget err: %v", err)
    60  		return
    61  	}
    62  	fmt.Println("\n-----hmget results-----")
    63  	for _, v := range values {
    64  		fmt.Println(string(v))
    65  	}
    66  
    67  	res, err := db.HDel([]byte("my_hash"), []byte("f1"))
    68  	if err != nil {
    69  		fmt.Printf("hdel err: %v", err)
    70  		return
    71  	}
    72  	fmt.Println("hdel result : ", res)
    73  }