Preface
For more information about indexeddb, see
Indexed Database API (W3C) s using_indexeddb (MDN) and use indexeddb
(Chinese ).
I have carefully reviewed the W3C API to find out what is going on with indexeddb indexes. I did not discuss the use of indexes in the above two link tutorials.
An index is used to quickly query data.
This article shows how to create and use indexes in indexeddb to optimize data queries. In the indexeddb tutorials searched on the internet, I did not describe the use of indexes, Or I did not mention how to create indexes. Here is a simple and complete example to demonstrate how to use indexeddb indexes.
Example of index requirements
Suppose there is a set of the following data:
ID name
1 zhangsan
2 sheets, 4 sheets
3 zhangwu
Four sheets, six sheets
5 Wang Wu
6 Wang 6
There are four surnamed Zhang and two surnamed Wang.
How can I quickly and conveniently query all records with the surname Zhang?
Use indexes for example requirements
If no index is required, all records are queried in the code, and each record is filtered by judgment.
If an index is used, all records of a specific surname can be investigated based on the specified parameter.
Sample code snippet for creating an index:
store.createIndex("ix_familyName", "familyName", {unique: false});
Sample code snippet for inserting test data:
Store. put ({familyname: "Zhang", name: "Zhang San"}); store. put ({familyname: "Zhang", name: "Zhang Si"}); store. put ({familyname: "Zhang", name: "Zhang Wu"}); store. put ({familyname: "", name: ""}); store. put ({familyname: "", name: ""}); store. put ({familyname: "", name: ""});
Sample code snippet for querying all records with the surname Zhang:
VaR keyrange = idbkeyrange. Only ("Zhang"); var Req = store. Index ("ix_familyname"). opencursor (keyrange );
The result will not contain records with other surnames.
Complete index DEMO code
[A complete demo that can be run can be found here]
<! Doctype HTML>