如何在 IndexedDB 中对重复项进行分组
How to group duplicates in IndexedDB
我如何为 indexedDB 构建这样的查询:
SELECT GROUP_CONCAT(id) as ids FROM contacts GROUP BY name HAVING count(name) > 1
我的目标是显示重复项。
您必须手动迭代,但使用索引按名称迭代:
在您的 "upgradeneeded" 处理程序中:
// Assumes records like {id: 1234, name: 'Beyoncé'}
var store = db.createObjectStore('contacts', {keyPath: 'id'});
var index = store.createIndex('by_name', 'name');
查询:
// Results end up here - this is map from name to array-of-ids:
var dupes = new Map();
var tx = db.transaction('contacts');
var index = tx.objectStore('contacts').index('by_name');
var req = index.openCursor();
var last;
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) return; // Done!
var name = cursor.key, id = cursor.primaryKey;
if (name === last) {
// It's a duplicate!
if (!dupes.has(name)) dupes.set(name, []);
dupes.get(name).push(id);
} else {
last = name;
}
cursor.continue();
};
我如何为 indexedDB 构建这样的查询:
SELECT GROUP_CONCAT(id) as ids FROM contacts GROUP BY name HAVING count(name) > 1
我的目标是显示重复项。
您必须手动迭代,但使用索引按名称迭代:
在您的 "upgradeneeded" 处理程序中:
// Assumes records like {id: 1234, name: 'Beyoncé'}
var store = db.createObjectStore('contacts', {keyPath: 'id'});
var index = store.createIndex('by_name', 'name');
查询:
// Results end up here - this is map from name to array-of-ids:
var dupes = new Map();
var tx = db.transaction('contacts');
var index = tx.objectStore('contacts').index('by_name');
var req = index.openCursor();
var last;
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) return; // Done!
var name = cursor.key, id = cursor.primaryKey;
if (name === last) {
// It's a duplicate!
if (!dupes.has(name)) dupes.set(name, []);
dupes.get(name).push(id);
} else {
last = name;
}
cursor.continue();
};