戻る

group byと同様の処理
indexedDB

このサンプルではgroup化するデータをあらかじめcreateIndexでまとめています。
このデータを使ってgroup byをした結果を返すカーソルを使用した処理となります。
メモリでソートをすると大きいデータの場合メモリ負荷が増え、圧迫されてしまうことから
複合インデックスを準備してソートをする方法となります。

[サンプル]
copy
async function testGroupBy(dbName, storeName) 
{
	const db = await databaseOpen(dbName);
	const rows = await runTx(db, storeName, "readonly", (store) => 
	{
		return new Promise((resolve, reject) => {
		const index = store.index("f1_f2");
		const groupedData = [];
		const req = index.openCursor();
		let key = "";
		req.onsuccess = (event) => 
		{
			const cursor = event.target.result;
			if (cursor) 
			{
				const tmp = cursor.value;
				//const category = record.f1_f2;
				const category = tmp.f1 + "" + tmp.f2;
				//console.log("i:"+idx+" category:"+category);
				if (!groupedData[category]) 
				{
					groupedData.push(category);
				}
				//next record
				cursor.continue();
			} 
			else 
			{
				//cursor end
				resolve(groupedData);
			}
		};
			req.onerror = () => reject(req.error);
		});
	});
	
	db.close();

	return rows;
}
function waitForTx(tx) 
{
	return new Promise((resolve, reject) => 
	{
		tx.oncomplete = () => resolve();
		tx.onabort = () => reject(tx.error ?? new Error("Transaction aborted"));
		tx.onerror = () => reject(tx.error);
	});
}

async function runTx(db, storeName, mode, work) 
{
	const tx = db.transaction([storeName], mode);
	const store = tx.objectStore(storeName);
	const result = await work(store);
	await waitForTx(tx);
	return result;
}

function openDatabase(dbName, version, upgrade) 
{
	return new Promise((resolve, reject) => 
	{
		const req = indexedDB.open(dbName, version);
		req.onupgradeneeded = (event) => 
		{
			const db = event.target.result;
			upgrade?.(db, event);
		};
		req.onsuccess = (event) => 
		{
			resolve(event.target.result);
		};
		req.onerror = () => reject(req.error);
	});
}
testGroupBy("aaa", "t2")
.then(rows => 
{
	for(i=0;i < rows.length;i++)
	{
		console.log("i:"+i+" rows:"+rows[i]);
	}
})
.catch(error => {
	console.error("group by error:", error);
});

このサンプルでは下記のようにオブジェクトスキーマを実装しています。
const store = db.createObjectStore("t2", { keyPath: "f0" });
store.createIndex("f1", "f1", { unique: false });
store.createIndex("f2", "f2", { unique: false });
store.createIndex("f3", "f3", { unique: false });
store.createIndex("f4", "f4", { unique: false });
//追加:f1 → f2 の並び
store.createIndex("f1_f2", ["f1", "f2"]);
上記レイアウトを使用してカーソルを使用してブレイクしたデータを配列に格納していきます。

const index = store.index("f1_f2");
const req = index.openCursor();
複合インデックスでカーソルを開きます。

const category = tmp.f1 + "" + tmp.f2;
グループ化したものとしてf1フィールドとf2フィールドを結合したカテゴリを変数にします。

if (!groupedData[category])
配列に先ほど取得したカテゴリ変数がないか?を判定します。
存在しない場合は配列として追加します。

cursor.continue();
次のカーソルに進めます。


戻る


著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。