IndexedDB 是面向对象的数据库,而不是关系数据库。与 SQL 表最接近的类似物是对象存储,使用 IDBDatabase.createObjectStore 创建。对象存储没有固定模式,因此对IDBObjectStore.put 的调用可以接受具有任何字段的对象,只要该对象具有keyPath 字段或通过设置{autoIncrement: true} 使keyPath 成为可选。默认情况下,您只能使用keyPath 查询文档。要使用其他字段查询文档,必须使用IDBObjectStore.createIndex创建索引
这是一个使用号码或姓名前缀查找联系人的应用程序的摘录。
dbReq.onupgradeneeded = function (event) {
var db = event.target.result,
objectStore = db.createObjectStore('calls', {keyPath: 'timestamp'}),
contactStore = db.createObjectStore('contacts', {autoIncrement: true});
objectStore.createIndex('number', 'number', {unique: false});
contactStore.createIndex('number', 'number');
contactStore.createIndex('name', 'name', {unique: false});
objectStore.createIndex('timestamp', 'timestamp', {unique: true});
};
按前缀查找:
findPrefix: function(prefix, fn) {
var transaction = this.db.transaction(['contacts', 'calls']),
contactStore = transaction.objectStore('contacts'),
callStore = transaction.objectStore('calls'),
numberIndex = callStore.index('number'),
nameIndex = contactStore.index('name'),
key = IDBKeyRange.bound(prefix, prefix + '\uffff'),
times = 0,
result = [],
consume = function(records) {
result = result.concat(records);
if (++times === 2) {
/* Remove duplicate numbers: names and numbers may have the same value*/
var numbers = {};
result = result.filter(function(contact) {
if (!numbers[contact.number]) {
return (numbers[contact.number] = true);
}
return false;
});
fn(result);
}
};
this.consumeCursor(numberIndex.openCursor(key, 'nextunique'), consume);
this.consumeCursor(nameIndex.openCursor(key), consume);
}
More on IndexedDB