Search code examples
redisredisjson

Using ReJson to store a numerical tree


I would like to insert fixed-length numerical values in a tree and check their presence at a later point. Most of the numerical values are similar so it does not make sense to put them in a SET since I would be wasting space.

Since ReJson PATH expects "Java-like" naming convention for key names, this is what I came up with:

{
  "_0": {
    "_1": {
      "_2": true
    }
  },
  "_2": {
    "_3": {
      "_4": true
    }
  }
}

So, when I need to know if "012" has been set, I need to do check if "JSON.GET key ._0._1._2" == true.

Initially, I tried saving the natural tree values such as:

{
  "0": {
    "1": {
      "2": true
    }
  },
  "2": {
    "3": {
      "4": true
    }
  }
}

But I cannot write any PATH that would be able to traverse this tree, neither in dot nor in bracket form.

Any suggestions? Should I stick to my underscored values and ._a._b._c pattern or is there a better way?


Solution

  • ReJSON uses paths that are JSONPath-like (but not exactly). Specifically, the docs state that "Names must begin with a letter, a dollar ($) or an underscore (_) character". This means that your second tree is not supported.

    While ReJSON could be used to store a tree-like structure, it looks like your use case would not benefit from using it. Instead, I'd look into flattening the tree and storing it as a Hash (or even a Set), where each field represents a path, e.g.:

    HSET tree 0.1.2 1 2.3.4 1
    

    Then you can use something like HEXISTS to check for "truthiness".