Search code examples
postgresqltypeorm

Postgresql full text search with TypeOrm


There is some way to handle full text search with Postgres and TypeOrm. I've seen some examples but they only work with Mysql. How can I get the equivalent of this but with Postgresql?

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: string;

    @Index({ fulltext: true })
    @Column("varchar")
    name: string;
}

And use query builder:

const searchTerm = "John";

const result = await connection.manager.getRepository(User)
            .createQueryBuilder()
            .select()
            .where(`MATCH(name) AGAINST ('${searchTerm}' IN BOOLEAN MODE)`)
            .getMany();

Solution

  • For case insensitive searches I usually use the ILIKE PostgreSQL expression. eg;

    const searchTerm = "John";
    
    const result = await connection.manager.getRepository(User)
      .createQueryBuilder()
      .select()
      .where('name ILIKE :searchTerm', {searchTerm: `%${searchTerm}%`})
      .getMany();
    

    Or if you had first and last name columns.

    const result = await connection.manager.getRepository(User)
      .createQueryBuilder()
      .select()
      .where('first_name ILIKE :searchTerm', {searchTerm: `%${searchTerm}%`})
      .orWhere('last_name ILIKE :searchTerm', {searchTerm: `%${searchTerm}%`})
      .getMany();