MariaDBデータベースへのバルクインサート:TypeORMでパフォーマンスを向上させる

2024-04-21

Express、MariaDB、バックエンドにおけるTypeORMでのバルクインサート

TypeORMは、Node.jsとTypeScript向けの人気のあるオブジェクトリレーショナルマッピング(ORM)フレームワークです。ExpressバックエンドとMariaDBデータベースを使用するアプリケーションでは、TypeORMを使用してデータを効率的に挿入する方法があります。特に、大量のデータを挿入する必要がある場合は、バルクインサートと呼ばれる手法が有効です。

バルクインサートは、個々のINSERTステートメントを実行する代わりに、一度に複数のレコードをデータベースに挿入するテクニックです。これは、大量のデータを挿入する場合にパフォーマンスを大幅に向上させることができます。

TypeORMには、バルクインサートを実行するためのいくつかの方法があります。

  • save()メソッド

save()メソッドは、エンティティオブジェクトを保存するために使用できます。個々のオブジェクトを保存するだけでなく、配列またはオブジェクトの配列を渡して複数のオブジェクトを保存することもできます。

const userRepository = await getRepository(User);
const users = [
  { name: 'John Doe', email: '[email protected]' },
  { name: 'Jane Doe', email: '[email protected]' },
];
await userRepository.save(users);
  • クエリビルダー

クエリビルダーは、より複雑なクエリを作成するために使用できます。バルクインサートを実行するには、insert()メソッドを使用します。

const userRepository = await getRepository(User);
const users = [
  { name: 'John Doe', email: '[email protected]' },
  { name: 'Jane Doe', email: '[email protected]' },
];
await userRepository.createQueryBuilder()
  .insert()
  .values(users)
  .execute();
  • ネイティブSQL

ネイティブSQLを使用してバルクインサートを実行することもできます。

const entityManager = await getManager();
await entityManager.query('INSERT INTO users (name, email) VALUES (?, ?)', ['John Doe', '[email protected]']);
await entityManager.query('INSERT INTO users (name, email) VALUES (?, ?)', ['Jane Doe', '[email protected]']);

MariaDBでのバルクインサート

MariaDBは、INSERTステートメントのバッチングをサポートしています。これは、TypeORMを使用してバルクインサートを実行する場合にパフォーマンスをさらに向上させることができます。

const connection = await createConnection({
  type: 'mariadb',
  host: 'localhost',
  database: 'mydatabase',
  username: 'root',
  password: 'password',
});
const userRepository = connection.getRepository(User);
const users = [
  { name: 'John Doe', email: '[email protected]' },
  { name: 'Jane Doe', email: '[email protected]' },
];
await userRepository.save(users, { chunk: 100 });

TypeORMは、ExpressバックエンドとMariaDBデータベースを使用するアプリケーションでバルクインサートを実行するための柔軟な方法を提供します。ニーズに最適な方法を選択してください。




Express、MariaDB、バックエンドにおけるTypeORMでのバルクインサート - サンプルコード

エンティティ定義

まず、Userエンティティを定義する必要があります。

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  email: string;
}

データ挿入

次に、以下のコードを使用してデータを挿入します。

import { createConnection } from 'typeorm';
import { User } from './user.entity';

(async () => {
  const connection = await createConnection({
    type: 'mariadb',
    host: 'localhost',
    database: 'mydatabase',
    username: 'root',
    password: 'password',
  });

  const userRepository = connection.getRepository(User);

  // 個々のオブジェクトを保存
  const user1 = new User();
  user1.name = 'John Doe';
  user1.email = '[email protected]';
  await userRepository.save(user1);

  const user2 = new User();
  user2.name = 'Jane Doe';
  user2.email = '[email protected]';
  await userRepository.save(user2);

  // オブジェクトの配列を保存
  const users = [
    { name: 'Peter Jones', email: '[email protected]' },
    { name: 'Mary Smith', email: '[email protected]' },
  ];
  await userRepository.save(users);

  // QueryBuilderを使用して保存
  const qb = userRepository.createQueryBuilder();
  qb.insert()
    .values([
      { name: 'John Doe', email: '[email protected]' },
      { name: 'Jane Doe', email: '[email protected]' },
    ])
    .execute();

  // ネイティブSQLを使用して保存
  await connection.query('INSERT INTO users (name, email) VALUES (?, ?)', ['John Doe', '[email protected]']);
  await connection.query('INSERT INTO users (name, email) VALUES (?, ?)', ['Jane Doe', '[email protected]']);

  // バッチ挿入
  const usersToInsert = [
    { name: 'Peter Jones', email: '[email protected]' },
    { name: 'Mary Smith', email: '[email protected]' },
    { name: 'David Williams', email: '[email protected]' },
    { name: 'Sarah Johnson', email: '[email protected]' },
    { name: 'Michael Brown', email: '[email protected]' },
  ];
  await userRepository.save(usersToInsert, { chunk: 100 });

  console.log('Data inserted successfully');
})();

このコードは、以下の方法でデータを挿入します。

  • 個々のUserオブジェクトを保存する
  • QueryBuilderを使用してINSERTステートメントを構築して実行する
  • ネイティブSQLを使用してINSERTステートメントを実行する
  • バッチ挿入を使用して、一度に複数のレコードを挿入する
  • このコードは、Node.jsとTypeScriptを使用して記述されています。
  • MariaDBデータベースを使用する必要があります。
  • TypeORMをインストールする必要があります: npm install typeorm

このサンプルコードを参考に、ニーズに合った方法でTypeORMを使用してバルクインサートを実行してください。




TypeORMでのバルクインサート - その他の方法

トランザクションを使用すると、複数のINSERTステートメントを単一の操作としてグループ化できます。これは、データの一貫性を保証するのに役立ちます。

const userRepository = connection.getRepository(User);
const users = [
  { name: 'John Doe', email: '[email protected]' },
  { name: 'Jane Doe', email: '[email protected]' },
];

await userRepository.transaction(async (manager) => {
  for (const user of users) {
    await manager.save(user);
  }
});

insert()メソッドのオプションを使用する

insert()メソッドには、パフォーマンスを向上させるために使用できるいくつかのオプションがあります。

  • chunk: 一度に挿入するレコードの数を指定します。
  • ignoreDuplicates: 重複するレコードを無視します。
  • overwriteExisting: 既存のレコードを上書きします。
const userRepository = connection.getRepository(User);
const users = [
  { name: 'John Doe', email: '[email protected]' },
  { name: 'Jane Doe', email: '[email protected]' },
  { name: 'John Doe', email: '[email protected]' }, // 重複するレコード
];

await userRepository.insert(users, { chunk: 100, ignoreDuplicates: true });

ストアドプロシージャを使用する

データベースがストアドプロシージャをサポートしている場合は、ストアドプロシージャを使用してバルクインサートを実行できます。これは、複雑な挿入ロジックがある場合に役立ちます。

const connection = await createConnection({
  type: 'mariadb',
  host: 'localhost',
  database: 'mydatabase',
  username: 'root',
  password: 'password',
});

await connection.query('CALL insertUsers(?)', [[
  { name: 'John Doe', email: '[email protected]' },
  { name: 'Jane Doe', email: '[email protected]' },
]]);

express mariadb backend


Laravel 5.4 で MariaDB に接続: ステップバイステップガイド

以下の手順で、Laravel 5.4 アプリケーションで MariaDB に接続できます。必要なパッケージをインストールするまず、Composer を使用して mysql パッケージをインストールする必要があります。.env ファイルを編集する...


【保存版】MariaDBでエラー「can't create a table with two foreign keys」が発生したときの対処法

MariaDBでテーブルを作成する際、2つの外部キー制約を設定しようとするとエラーが発生することがあります。この問題は、いくつかの原因が考えられます。本記事では、**「MariaDB - can't create a table with two foreign keys」**というエラーの原因と、解決策について詳しく解説します。...


欠番のない完璧なシーケンスを実現:MySQLとMariaDBにおけるギャップ検出と修復のベストプラクティス

MySQLとMariaDBでは、連続した数値のシーケンスを生成する AUTO_INCREMENT 機能が提供されています。しかし、データ挿入時に欠番が発生することがあります。このような場合、最初の欠番を効率的に検出することが重要になります。...


MariaDB 初心者向け!Mac Big Sur で MariaDB をインストール・設定する方法

原因: この問題は、Homebrew でインストールされた以前のバージョンの MySQL と MariaDB の競合が原因である可能性があります。解決策: 以下の手順で問題を解決できます。古い MySQL インストールを削除する:MariaDB を再インストールする:...


MariaDB の InnoDB リードバッファ効率が 0% の原因と解決策

MariaDB で InnoDB リードバッファ効率が 0% になっている場合、データベースのパフォーマンスが著しく低下する可能性があります。これは、InnoDB リードバッファがほとんど使用されていないことを意味し、データベースがディスク I/O に依存してデータをを読み取っているためです。...