rejson

package module
v4.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 31, 2023 License: MIT Imports: 3 Imported by: 28

README

Note: Currently, go-ReJSON only support redislabs/rejson with version <=1.0.8. If you are using higher versions, some commands might not work as expected

Go-ReJSON - a golang client for ReJSON (a JSON data type for Redis)

Go-ReJSON is a Go client for ReJSON Redis Module.

Go Reference test code-analysis codecov Go Report Card GitHub release

ReJSON is a Redis module that implements ECMA-404 The JSON Data Interchange Standard as a native data type. It allows storing, updating and fetching JSON values from Redis keys (documents).

Primary features of ReJSON Module:

* Full support of the JSON standard
* JSONPath-like syntax for selecting element inside documents
* Documents are stored as binary data in a tree structure, allowing fast access to sub-elements
* Typed atomic operations for all JSON values types

Each and every feature of ReJSON Module is fully incorporated in the project.

Enjoy ReJSON with the type-safe Redis client, Go-Redis/Redis or use the print-like Redis-api client GoModule/Redigo. Go-ReJSON supports both the clients. Use any of the above two client you want, Go-ReJSON helps you out with all its features and functionalities in a more generic and standard way.

Support for mediocregopher/radix and other Redis clients is in our RoadMap. Any contributions to the support for other clients is hearty welcome.

Installation

go get github.com/nitishm/go-rejson/v4

Example usage

package main

import (
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"log"

	"github.com/nitishm/go-rejson/v4"
	goredis "github.com/go-redis/redis/v8"
	"github.com/gomodule/redigo/redis"
)

// Name - student name
type Name struct {
	First  string `json:"first,omitempty"`
	Middle string `json:"middle,omitempty"`
	Last   string `json:"last,omitempty"`
}

// Student - student object
type Student struct {
	Name Name `json:"name,omitempty"`
	Rank int  `json:"rank,omitempty"`
}

func Example_JSONSet(rh *rejson.Handler) {

	student := Student{
		Name: Name{
			"Mark",
			"S",
			"Pronto",
		},
		Rank: 1,
	}
	res, err := rh.JSONSet("student", ".", student)
	if err != nil {
		log.Fatalf("Failed to JSONSet")
		return
	}

	if res.(string) == "OK" {
		fmt.Printf("Success: %s\n", res)
	} else {
		fmt.Println("Failed to Set: ")
	}

	studentJSON, err := redis.Bytes(rh.JSONGet("student", "."))
	if err != nil {
		log.Fatalf("Failed to JSONGet")
		return
	}

	readStudent := Student{}
	err = json.Unmarshal(studentJSON, &readStudent)
	if err != nil {
		log.Fatalf("Failed to JSON Unmarshal")
		return
	}

	fmt.Printf("Student read from redis : %#v\n", readStudent)
}

func main() {
	var addr = flag.String("Server", "localhost:6379", "Redis server address")

	rh := rejson.NewReJSONHandler()
	flag.Parse()

	// Redigo Client
	conn, err := redis.Dial("tcp", *addr)
	if err != nil {
		log.Fatalf("Failed to connect to redis-server @ %s", *addr)
	}
	defer func() {
		_, err = conn.Do("FLUSHALL")
		err = conn.Close()
		if err != nil {
			log.Fatalf("Failed to communicate to redis-server @ %v", err)
		}
	}()
	rh.SetRedigoClient(conn)
	fmt.Println("Executing Example_JSONSET for Redigo Client")
	Example_JSONSet(rh)

	// GoRedis Client
	cli := goredis.NewClient(&goredis.Options{Addr: *addr})
	defer func() {
		if err := cli.FlushAll(context.Background()).Err(); err != nil {
			log.Fatalf("goredis - failed to flush: %v", err)
		}
		if err := cli.Close(); err != nil {
			log.Fatalf("goredis - failed to communicate to redis-server: %v", err)
		}
	}()
	rh.SetGoRedisClient(cli)
	fmt.Println("\nExecuting Example_JSONSET for GoRedis Client")
	Example_JSONSet(rh)
}

Documentation

Overview

Go-ReJSON is a Go client for ReJSON redis module (https://github.com/RedisLabsModules/rejson)

ReJSON is a Redis module that aims to provide full support for ECMA-404
The JSON Data Interchange Standard as a native data type.

It allows storing, updating and fetching JSON values from Redis keys (documents).

Primary features of ReJSON Module:
	* Full support of the JSON standard
	* JSONPath-like syntax for selecting element inside documents
	* Documents are stored as binary data in a tree structure, allowing fast access
	  to sub-elements
	* Typed atomic operations for all JSON values types

Go-ReJSON implements all the features of ReJSON Module, without any dependency on the client used for Redis in GoLang.

Enjoy ReJSON with the type-safe Redis client, Go-Redis/Redis (https://github.com/go-redis/redis) or use the print-like Redis-api client GoModule/Redigo (https://github.com/gomodule/redigo/redis).

Go-ReJSON supports both the clients. Use any of the above two client you want, Go-ReJSON helps you out with all its features and functionalities in a more generic and standard way.

Installation

To install and use ReJSON module, one must have the pre-requisites installed and setup. Run the script in :

./install-redis-rejson.sh

Examples

Create New ReJSON Handler

rh := rejson.NewReJSONHandler()

Set Redigo Client and use ReJSON in it

conn, _ := redis.Dial("tcp", *addr)
rh.SetRedigoClient(conn)

Similarly, one can set client for Go-Redis

cli := goredis.NewClient(&goredis.Options{Addr: *addr})
rh.SetGoRedisClient(cli)

And now, one can directly use ReJSON commands using the handler

res, err := rh.JSONSet("str", ".", "string")

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

func NewReJSONHandler

func NewReJSONHandler() *Handler

func (*Handler) JSONArrAppend

func (r *Handler) JSONArrAppend(key, path string, values ...interface{}) (res interface{}, err error)

JSONArrAppend to append json value into array at path

ReJSON syntax:

JSON.ARRAPPEND <key> <path> <json> [json ...]

func (*Handler) JSONArrIndex

func (r *Handler) JSONArrIndex(key, path string, jsonValue interface{}, optionalRange ...int) (
	res interface{}, err error,
)

JSONArrIndex returns the index of the json element provided and return -1 if element is not present

ReJSON syntax:

JSON.ARRINDEX <key> <path> <json-scalar> [start [stop]]

func (*Handler) JSONArrInsert

func (r *Handler) JSONArrInsert(key, path string, index int, values ...interface{}) (res interface{}, err error)

JSONArrInsert inserts the json value(s) into the array at path before the index (shifts to the right).

ReJSON syntax:

JSON.ARRINSERT <key> <path> <index> <json> [json ...]

func (*Handler) JSONArrLen

func (r *Handler) JSONArrLen(key, path string) (res interface{}, err error)

JSONArrLen returns the length of the json array at path

ReJSON syntax:

JSON.ARRLEN <key> [path]

func (*Handler) JSONArrPop

func (r *Handler) JSONArrPop(key, path string, index int) (res interface{}, err error)

JSONArrPop removes and returns element from the index in the array to pop last element use rejson.PopArrLast

ReJSON syntax:

JSON.ARRPOP <key> [path [index]]

func (*Handler) JSONArrTrim

func (r *Handler) JSONArrTrim(key, path string, start, end int) (res interface{}, err error)

JSONArrTrim trims an array so that it contains only the specified inclusive range of elements

ReJSON syntax:

JSON.ARRTRIM <key> <path> <start> <stop>

func (*Handler) JSONDebug

func (r *Handler) JSONDebug(subCmd rjs.DebugSubCommand, key, path string) (res interface{}, err error)

JSONDebug reports information

ReJSON syntax:

JSON.DEBUG <subcommand & arguments>
	JSON.DEBUG MEMORY <key> [path]	- report the memory usage in bytes of a value. path defaults to root if not provided.
	JSON.DEBUG HELP					- reply with a helpful message

func (*Handler) JSONDel

func (r *Handler) JSONDel(key string, path string) (res interface{}, err error)

JSONDel to delete a json object

ReJSON syntax:

JSON.DEL <key> <path>

func (*Handler) JSONForget

func (r *Handler) JSONForget(key, path string) (res interface{}, err error)

JSONForget is an alias for JSONDel

ReJSON syntax:

JSON.FORGET <key> [path]

func (*Handler) JSONGet

func (r *Handler) JSONGet(key, path string, opts ...rjs.GetOption) (res interface{}, err error)

JSONGet used to get a json object

ReJSON syntax:

JSON.GET <key>
		[INDENT indentation-string]
		[NEWLINE line-break-string]
		[SPACE space-string]
		[NOESCAPE]
		[path ...]

func (*Handler) JSONMGet

func (r *Handler) JSONMGet(path string, keys ...string) (res interface{}, err error)

JSONMGet used to get path values from multiple keys

ReJSON syntax:

JSON.MGET <key> [key ...] <path>

func (*Handler) JSONNumIncrBy

func (r *Handler) JSONNumIncrBy(key, path string, number int) (res interface{}, err error)

JSONNumIncrBy to increment a number by provided amount

ReJSON syntax:

JSON.NUMINCRBY <key> <path> <number>

func (*Handler) JSONNumMultBy

func (r *Handler) JSONNumMultBy(key, path string, number int) (res interface{}, err error)

JSONNumMultBy to increment a number by provided amount

ReJSON syntax:

JSON.NUMMULTBY <key> <path> <number>

func (*Handler) JSONObjKeys

func (r *Handler) JSONObjKeys(key, path string) (res interface{}, err error)

JSONObjKeys returns the keys in the object that's referenced by path

ReJSON syntax:

JSON.OBJKEYS <key> [path]

func (*Handler) JSONObjLen

func (r *Handler) JSONObjLen(key, path string) (res interface{}, err error)

JSONObjLen report the number of keys in the JSON Object at path in key

ReJSON syntax:

JSON.OBJLEN <key> [path]

func (*Handler) JSONResp

func (r *Handler) JSONResp(key, path string) (res interface{}, err error)

JSONResp returns the JSON in key in Redis Serialization Protocol (RESP).

ReJSON syntax:

JSON.RESP <key> [path]

func (*Handler) JSONSet

func (r *Handler) JSONSet(key string, path string, obj interface{}, opts ...rjs.SetOption) (
	res interface{}, err error,
)

JSONSet used to set a json object

ReJSON syntax:

JSON.SET <key> <path> <json>
		 [NX | XX]

func (*Handler) JSONStrAppend

func (r *Handler) JSONStrAppend(key, path, jsonstring string) (res interface{}, err error)

JSONStrAppend to append a jsonstring to an existing member

ReJSON syntax:

JSON.STRAPPEND <key> [path] <json-string>

func (*Handler) JSONStrLen

func (r *Handler) JSONStrLen(key, path string) (res interface{}, err error)

JSONStrLen to return the length of a string member

ReJSON syntax:

JSON.STRLEN <key> [path]

func (*Handler) JSONType

func (r *Handler) JSONType(key, path string) (res interface{}, err error)

JSONType to get the type of key or member at path.

ReJSON syntax:

JSON.TYPE <key> [path]

func (*Handler) SetClientInactive

func (r *Handler) SetClientInactive()

SetClientInactive resets the handler and unset any client, set to the handler

func (*Handler) SetContext

func (r *Handler) SetContext(ctx context.Context) *Handler

SetContext helps redis-clients, provide use of command level context in the ReJSON commands. Currently, only go-redis@v8 supports command level context, therefore a separate method is added to support it, maintaining the support for other clients and for backward compatibility. (nitishm/go-rejson#46)

func (*Handler) SetGoRedisClient deprecated

func (r *Handler) SetGoRedisClient(conn clients.GoRedisClientConn)

Deprecated: SetGoRedisClient sets Go-Redis (https://github.com/go-redis/redis) client to the handler. It is left for backward compatibility.

func (*Handler) SetGoRedisClientWithContext

func (r *Handler) SetGoRedisClientWithContext(ctx context.Context, conn clients.GoRedisClientConn)

SetGoRedisClientWithContext sets Go-Redis (https://github.com/go-redis/redis) client to the handler with a global context for the connection

func (*Handler) SetRedigoClient

func (r *Handler) SetRedigoClient(conn clients.RedigoClientConn)

SetRedigoClient sets Redigo (https://github.com/gomodule/redigo/redis) client to the handler

type ReJSON

type ReJSON interface {
	JSONSet(key, path string, obj interface{}, opts ...rjs.SetOption) (res interface{}, err error)

	JSONGet(key, path string, opts ...rjs.GetOption) (res interface{}, err error)

	JSONMGet(path string, keys ...string) (res interface{}, err error)

	JSONDel(key, path string) (res interface{}, err error)

	JSONType(key, path string) (res interface{}, err error)

	JSONNumIncrBy(key, path string, number int) (res interface{}, err error)

	JSONNumMultBy(key, path string, number int) (res interface{}, err error)

	JSONStrAppend(key, path string, jsonstring string) (res interface{}, err error)

	JSONStrLen(key, path string) (res interface{}, err error)

	JSONArrAppend(key, path string, values ...interface{}) (res interface{}, err error)

	JSONArrLen(key, path string) (res interface{}, err error)

	JSONArrPop(key, path string, index int) (res interface{}, err error)

	JSONArrIndex(key, path string, jsonValue interface{}, optionalRange ...int) (res interface{}, err error)

	JSONArrTrim(key, path string, start, end int) (res interface{}, err error)

	JSONArrInsert(key, path string, index int, values ...interface{}) (res interface{}, err error)

	JSONObjKeys(key, path string) (res interface{}, err error)

	JSONObjLen(key, path string) (res interface{}, err error)

	JSONDebug(subCmd rjs.DebugSubCommand, key, path string) (res interface{}, err error)

	JSONForget(key, path string) (res interface{}, err error)

	JSONResp(key, path string) (res interface{}, err error)
}

ReJSON provides an interface for various Go Redis Clients to implement ReJSON commands

type RedisClient

type RedisClient interface {
	SetClientInactive()
	SetRedigoClient(conn clients.RedigoClientConn)
	SetGoRedisClient(conn clients.GoRedisClientConn)
}

RedisClient provides interface for Client handling in the ReJSON Handler

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL