redis / redis-om-node

Object mapping, and more, for Redis and Node.js. Written in TypeScript.
MIT License
1.17k stars 78 forks source link

How to store an array of objects in Redis? #209

Open Ericokim opened 1 year ago

Ericokim commented 1 year ago

I have an array of Objects that I want to store in Redis. How do i go about it?

guyroyse commented 1 year ago

Redis OM can support this but searching it can be a bit limited as you can only reference the fields within the objects for indexing and they will always be arrays as far as RediSearch is concerned. This means that you can only index string[] and number[] within your object.

Here's a quick example for the following JSON:

{
  "accountNumber": "12345",
  "verified": true,
  "transactions": [
    {
      "approver": "Alice",
      "amount": 12.34,
      "posted": true
    },
    {
      "approver": "Bob",
      "amount": 34.56,
      "posted": false
    }
  ]
}

We can search on all of these fields except posted. We can still save it, we just can't search on it. Here's what the Schema would look like:

const schema = new Schema('account', {
  accountNumber: { type: 'string' },
  verified: { type: 'boolean' },
  approvers: { type: 'string[]', path: '$.transactions[*].approver' },
  amounts: { type: 'number[]', path: '$.transactions[*].amount' }
})

You can then save this JSON and search on these fields with your Repository:

const repository = new Respository(schema, redis)

await respository.save(account) // account contains a JavaScript object as shown above

const accounts = await repository.search()
  .where('accountNumber').equals('12345')
    .and('verified').is.true()
    .and('approvers').contains('Bob')
    .and('amount').is.greaterThan(10.00)