TypeORM

TypeORM - data-mapper ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL databases. Works in Node.JS and Browser.

Indices

You can create database indices by using @Index decorator. You can use indices on both columns and classes. Using @Index decorator on columns allows to create index with single indexed field. Using @Index decorator on class allows to create index with multiple fields.


import {Entity, Index, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
@Index("my_index_with_id_and_text", ["id", "text"]) // first style
@Index("my_index_with_id_and_title", (post: Post) => [post.id, post.title]) // alternative, type-safe style
export class Post {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    @Index()
    title: string;

    @Column()
    text: string;

    @Column()
    @Index()
    likesCount: number;

}
        

First parameter to @Index decorator is index name. Second parameter array of properties you want this index to apply. This can be an array of strings - property names, or a function that returns array of property names. Second parameter can be used only if you are using @Index decorator on entity class.

Also you can set the index to be unique using special index option. Here is an example:


import {Entity, Index, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
@Index("my_index_with_id_and_text", ["id", "text"], { unique: true }) // first style
@Index("my_index_with_id_and_title", (post: Post) => [post.id, post.title], { unique: true }) // alternative, type-safe style
export class Post {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    @Index()
    title: string;

    @Column()
    text: string;

    @Column()
    @Index({ unique: true })
    likesCount: number;

}
        
Fork me on GitHub