Search code examples
redisredisjson

Is it possible to use LRANGE in rejson array?


I have a Redis-Server with rejson and want to retrieve a part of a nested array.

The array keeps getting bigger, because I add data with a background job. But I don't need all of the information, only a part of it. But there seems to be no JSON.ARRRANGE or "LRANGE" or something. Is there an other way of archiving that?

Example object structure:

{ 
 cars:
[
      {company: "Ford", timestamp:"123133131" },
      {company: "Mercedes", timestamp:"12165433131" },
],
 planes: 
[
      {company: "Foo", timestamp:"3123213114"},
      {company: "Bar", timestamp:"3123213114"},
]
}

I would like to access the cars array, but only a part of it, let's say the most recent 300.

I am a redis beginner, so maybe its possible to "query" the data somehow.

Thank you very much!


Solution

  • You can achieve this with minor modification in how you store your data. 1/ Store cars, planes etc in seperate redis LISTS . so for key “cars”, your redis list would look like this :

    [
          {company: "Ford", timestamp:"123133131" },
          {company: "Mercedes", timestamp:"12165433131" },
            ………………. MORE CARS …………
    ],
    

    similarly a seperate LIST for planes.

    2/ Now whenever you append an element to cars LIST using LPUSH, you can do an LTRIM till N to have only recentmost N records in the list.

    You can even optimize on number of LTRIM operations ( instead of doing it everytime after a LPUSH to add the element) : https://stackoverflow.com/a/37875025/533399