Javascript:使用多个索引搜索indexeddb [英] Javascript: Searching indexeddb using multiple indexes

查看:698
本文介绍了Javascript:使用多个索引搜索indexeddb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从WebSql更改为Indexeddb。但是,如何进行SQL查询,如

I want to change from WebSql to Indexeddb. However, how would one do SQL queries like

SELECT * FROM customers WHERE ssn = '444-44-4444' and emal = 'bill@bill@company.com'
SELECT * FROM customers WHERE ssn = '444-44-4444' and emal = 'bill@bill@company.com' and age = 30
SELECT * FROM customers WHERE ssn = '444-44-4444' and emal = 'bill@bill@company.com' and name = 'Bill'
etc

使用IndexedDB?
例如,我在阅读indexedDb的文档时注意到了,所有示例当时只查询一个索引。所以你可以做到

with IndexedDB ? For example, I noticed while reading the documentation of indexedDb, that all the examples only query one index at the time. So you can do

var index = objectStore.index("ssn");
index.get("444-44-4444").onsuccess = function(event) {
     alert("Name is " + event.target.result.name);
};

但我需要同时查询多个索引!

But I need to query multiple indexes at the same time!

我还发现了一些关于复合索引的有趣帖子,但它们只适用于你查询复合索引中的所有字段。

I also found some interesting posts about compound indexes, but they only work if you query for all the fields in the compound index.

推荐答案

对于您的示例,复合索引仍然有效,但需要两个复合索引

For your example, compound index still work, but requires two compound indexes

 objectStore.createIndex('ssn, email, age', ['ssn', 'email', 'age']); // corrected
 objectStore.createIndex('ssn, email, name', ['ssn', 'email', 'name'])

并且像这样查询

 keyRange = IDBKeyRange.bound(
     ['444-44-4444', 'bill@bill@company.com'],
     ['444-44-4444', 'bill@bill@company.com', '']) 
 objectStore.index('ssn, email, age').get(keyRange)
 objectStore.index('ssn, email, age').get(['444-44-4444', 'bill@bill@company.com', 30])
 objectStore.index('ssn, email, name').get(['444-44-4444', 'bill@bill@company.com', 'Bill'])

索引可以按任何顺序排列,但如果最具体的话,它是最有效的。

Indexes can be arranged in any order, but it is most efficient if most specific come first.

或者,您也可以使用密钥加入。密钥连接需要四个(单个)索引。四个索引占用的存储空间更少,更通用。例如,以下查询需要另一个复合索引

Alternatively, you can also use key joining. Key joining requires four (single) indexes. Four indexes take less storage space and more general. For example, the following query require another compound index

SELECT * FROM customers WHERE ssn = '444-44-4444' and name = 'Bill' and age = 30

密钥加入仍然适用于该查询。

Key joining still work for that query.

这篇关于Javascript:使用多个索引搜索indexeddb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆