HTML5本地存儲——IndexedDB(二:索引)

HTML5本地存儲——IndexedDB(一:基本使用)中介紹了關於IndexedDB的基本使用方法,很不過癮,這篇咱們來看看indexedDB的殺器——索引。javascript

熟悉數據庫的同窗都知道索引的一個好處就是能夠迅速定位數據,提升搜索速度,在indexedDB中有兩種索引,一種是自增加的int值,一種是keyPath:本身指定索引列,咱們重點來看看keyPath方式的索引使用.html

建立索引

咱們能夠在建立object store的時候指明索引,使用object store的createIndex建立索引,方法有三個參數java

  • 索引名稱
  • 索引屬性字段名
  • 索引屬性值是否惟一
function openDB (name,version) {
            var version=version || 1;
            var request=window.indexedDB.open(name,version);
            request.onerror=function(e){
                console.log(e.currentTarget.error.message);
            };
            request.onsuccess=function(e){
                myDB.db=e.target.result;
            };
            request.onupgradeneeded=function(e){
                var db=e.target.result;
                if(!db.objectStoreNames.contains('students')){
                    var store=db.createObjectStore('students',{keyPath: 'id'});
                    store.createIndex('nameIndex','name',{unique:true}); 
                    store.createIndex('ageIndex','age',{unique:false}); 
                }
                console.log('DB version changed to '+version);
            };
        }

這樣咱們在students 上建立了兩個索引數據庫

image

 

image

利用索引獲取數據

function getDataByIndex(db,storeName){
            var transaction=db.transaction(storeName);
            var store=transaction.objectStore(storeName);
            var index = store.index("nameIndex");
            index.get('Byron').onsuccess=function(e){
                var student=e.target.result;
                console.log(student.id);
            }
        }

這樣咱們能夠利用索引快速獲取數據,name的索引是惟一的沒問題,可是對於age索引只會取到第一個匹配值,要想獲得全部age符合條件的值就須要使用遊標了ide

遊標

在indexedDB中使用索引和遊標是分不開的,對數據庫熟悉的同窗很好理解遊標是什麼東東,有了數據庫object store的遊標,咱們就能夠利用遊標遍歷object store了。fetch

使用object store的openCursor()方法打開遊標spa

function fetchStoreByCursor(db,storeName){
            var transaction=db.transaction(storeName);
            var store=transaction.objectStore(storeName);
            var request=store.openCursor();
            request.onsuccess=function(e){
                var cursor=e.target.result;
                if(cursor){
                    console.log(cursor.key);
                    var currentStudent=cursor.value;
                    console.log(currentStudent.name);
                    cursor.continue();
                }
            };
        }

curson.contine()會使遊標下移,知道沒有數據返回undefined3d

index與遊標結合

 

要想獲取age爲26的student,能夠結合遊標使用索引code

function getMultipleData(db,storeName){
            var transaction=db.transaction(storeName);
            var store=transaction.objectStore(storeName);
            var index = store.index("ageIndex");
            var request=index.openCursor(IDBKeyRange.only(26))
            request.onsuccess=function(e){
                var cursor=e.target.result;
                if(cursor){
                    var student=cursor.value;
                    console.log(student.id);
                    cursor.continue();
                }
            }
        }

這樣咱們但是使用索引打開一個遊標,參數下面會講到,在成功的句柄內得到遊標便利age爲26的student,也能夠經過index.openKeyCursor()方法只獲取每一個對象的key值。htm

指定遊標範圍

index.openCursor()/index.openKeyCursor()方法在不傳遞參數的時候會獲取object store全部記錄,像上面例子同樣咱們能夠對搜索進行篩選
可使用key range 限制遊標中值的範圍,把它做爲第一個參數傳給  或是 openCursor()openKeyCursor()
IDBKeyRange.only(value):只獲取指定數據
IDBKeyRange.lowerBound(value,isOpen):獲取最小是value的數據,第二個參數用來指示是否排除value值自己,也就是數學中的是不是開區間
IDBKeyRange.upperBound(value,isOpen):和上面相似,用於獲取最大值是value的數據
IDBKeyRange.bound(value1,value2,isOpen1,isOpen2):不用解釋了吧

 

獲取名字首字母在B-E的student

function getMultipleData(db,storeName){
            var transaction=db.transaction(storeName);
            var store=transaction.objectStore(storeName);
            var index = store.index("nameIndex");
            var request=index.openCursor(IDBKeyRange.bound('B','F',false,
true
));
            request.onsuccess=function(e){
                var cursor=e.target.result;
                if(cursor){
                    var student=cursor.value;
                    console.log(student.name);
                    cursor.continue();
                }
            }
        }

 完整示例

 

  1 <!DOCTYPE HTML>
  2 <html>
  3 <head>
  4     <title>IndexedDB</title>
  5 </head>
  6 <body>
  7     <script type="text/javascript">
  8         function openDB (name,version) {
  9             var version=version || 1;
 10             var request=window.indexedDB.open(name,version);
 11             request.onerror=function(e){
 12                 console.log(e.currentTarget.error.message);
 13             };
 14             request.onsuccess=function(e){
 15                 myDB.db=e.target.result;
 16             };
 17             request.onupgradeneeded=function(e){
 18                 var db=e.target.result;
 19                 if(!db.objectStoreNames.contains('students')){
 20                     var store=db.createObjectStore('students',{keyPath: 'id'});
 21                     store.createIndex('nameIndex','name',{unique:true}); 
 22                     store.createIndex('ageIndex','age',{unique:false}); 
 23                 }
 24                 console.log('DB version changed to '+version);
 25             };
 26         }
 27 
 28         function closeDB(db){
 29             db.close();
 30         }
 31 
 32         function deleteDB(name){
 33             indexedDB.deleteDatabase(name);
 34         }
 35 
 36         function addData(db,storeName){
 37             var transaction=db.transaction(storeName,'readwrite'); 
 38             var store=transaction.objectStore(storeName); 
 39 
 40             for(var i=0;i<students.length;i++){
 41                 store.add(students[i]);
 42             }
 43         }
 44 
 45         function getDataByKey(db,storeName,value){
 46             var transaction=db.transaction(storeName,'readwrite'); 
 47             var store=transaction.objectStore(storeName); 
 48             var request=store.get(value); 
 49             request.onsuccess=function(e){ 
 50                 var student=e.target.result; 
 51                 console.log(student.name); 
 52             };
 53         }
 54 
 55         function updateDataByKey(db,storeName,value){
 56             var transaction=db.transaction(storeName,'readwrite'); 
 57             var store=transaction.objectStore(storeName); 
 58             var request=store.get(value); 
 59             request.onsuccess=function(e){ 
 60                 var student=e.target.result; 
 61                 student.age=35;
 62                 store.put(student); 
 63             };
 64         }
 65 
 66         function deleteDataByKey(db,storeName,value){
 67             var transaction=db.transaction(storeName,'readwrite'); 
 68             var store=transaction.objectStore(storeName); 
 69             store.delete(value); 
 70         }
 71 
 72         function clearObjectStore(db,storeName){
 73             var transaction=db.transaction(storeName,'readwrite'); 
 74             var store=transaction.objectStore(storeName); 
 75             store.clear();
 76         }
 77 
 78         function deleteObjectStore(db,storeName){
 79             var transaction=db.transaction(storeName,'versionchange'); 
 80             db.deleteObjectStore(storeName);
 81         }
 82 
 83         function fetchStoreByCursor(db,storeName){
 84             var transaction=db.transaction(storeName);
 85             var store=transaction.objectStore(storeName);
 86             var request=store.openCursor();
 87             request.onsuccess=function(e){
 88                 var cursor=e.target.result;
 89                 if(cursor){
 90                     console.log(cursor.key);
 91                     var currentStudent=cursor.value;
 92                     console.log(currentStudent.name);
 93                     cursor.continue();
 94                 }
 95             };
 96         }
 97 
 98         function getDataByIndex(db,storeName){
 99             var transaction=db.transaction(storeName);
100             var store=transaction.objectStore(storeName);
101             var index = store.index("ageIndex");
102             index.get(26).onsuccess=function(e){
103                 var student=e.target.result;
104                 console.log(student.id);
105             }
106         }
107 
108         function getMultipleData(db,storeName){
109             var transaction=db.transaction(storeName);
110             var store=transaction.objectStore(storeName);
111             var index = store.index("nameIndex");
112             var request=index.openCursor(null,IDBCursor.prev);
113             request.onsuccess=function(e){
114                 var cursor=e.target.result;
115                 if(cursor){
116                     var student=cursor.value;
117                     console.log(student.name);
118                     cursor.continue();
119                 }
120             }
121         }
122 
123         var myDB={
124             name:'test',
125             version:1,
126             db:null
127         };
128 
129         var students=[{ 
130             id:1001, 
131             name:"Byron", 
132             age:24 
133         },{ 
134             id:1002, 
135             name:"Frank", 
136             age:30 
137         },{ 
138             id:1003, 
139             name:"Aaron", 
140             age:26 
141         },{ 
142             id:1004, 
143             name:"Casper", 
144             age:26 
145         }]; 
146     </script>
147 </body>
148 </html>
View Code

 

 

最後

有了遊標和索引才能真正發揮indexedDB爲例,是否是感受比自定義對象強大方便了不少呢。

相關文章
相關標籤/搜索