Skip to main content

Key Compression

With the key compression plugin, documents will be stored in a compressed format which saves up to 40% disk space. For compression the npm module jsonschema-key-compression is used. It compresses json-data based on its json-schema while still having valid json. It works by compressing long attribute-names into smaller ones and backwards.

The compression and decompression happens internally, so when you work with a RxDocument, you can access any property like normal.

Long JSON keys compressed into short tokens

Enable key compression​

The key compression plugin is a wrapper around any other RxStorage.

1

Wrap your RxStorage with the key compression plugin​

import { wrappedKeyCompressionStorage } from 'rxdb/plugins/key-compression';
import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage';
 
const storageWithKeyCompression = wrappedKeyCompressionStorage({
    storage: getRxStorageLocalstorage()
});
2

Create an RxDatabase​

import { createRxDatabase } from 'rxdb/plugins/core';
const myDatabase = await createRxDatabase({
    name: 'mydatabase',
    storage: storageWithKeyCompression
});
3

Create a compressed RxCollection​

const todoSchema = {
  keyCompression: true, // set this to true, to enable the keyCompression
  version: 0,
  primaryKey: 'id',
  type: 'object',
  properties: {
      id: {
          type: 'string',
          maxLength: 100 // <- the primary key must have set maxLength
      },
      name: {
          type: 'string'
      },
      done: {
          type: 'boolean',
          default: false
      }
      /* ... */
  },
  required: ['id', 'name', 'done']
};
await myDatabase.addCollections({
    todos: {
        schema: todoSchema
    }
});
 
await myDatabase.todos.insert({ id: 'todo1', name: 'Learn RxDB' });
const doc = await myDatabase.todos.findOne('todo1').exec();
// the document data is decompressed when you access it
console.log(doc.name);
// > 'Learn RxDB'