Create and use indexes in indexeddb

Source: Internet
Author: User
Tags createindex
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> 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.