如何获取所有IDBIndex键值(而不是对象存储主键)?

时间:2018-12-03 09:36:00

标签: indexeddb

我有一个IndexedDB对象存储,其中包含一个主键和一个附加索引(具有唯一键约束)。

现在,我要检索此索引的所有键值。

以前,我使用IDBIndex.getAllKeys(),但此方法的行为似乎已更改为返回对象存储主键而不是索引键。 (但是,我找不到任何文档,也没有在浏览器发行说明中引用该信息……)

所以我的问题是: 推荐的,最高效的检索所有索引键值的方法是什么?

2 个答案:

答案 0 :(得分:1)

{'domain1': ['53/tcp,open,domain', '80/tcp,open,http'], 'domain2': ['22/tcp,open,ssh', '25/tcp,open,smtp', '80/tcp,open,http', '443/tcp,open,https'], 'domain3': ["22/tcp,open,ssh", "443/tcp,open,https"], 'domain4': ['80/tcp,open,http', '443/tcp,open,https'], 'domain5': ['80/tcp,open,http', '443/tcp,open,https']} 可以工作,但是会将所有值读入内存,这可能会很慢。

您是正确的,IDBIndex.getAll仅返回主键,而不返回索引键。

不幸的是,没有类似的单个函数可以返回索引键,但是您可以使用IDBIndex.getAllKeys并避免将值读入内存:

IDBIndex.openKeyCursor

我还没有对此进行基准测试,但是从理论上讲,它可能接近const result = []; index.openKeyCursor().onsuccess = (event) => { var cursor = event.target.result; if (cursor) { // cursor.key is the index key, cursor.primaryKey is the primary key, // and cursor.value is undefined because we're using openKeyCursor // rather than openCursor. result.push(cursor.key); cursor.continue(); } else { cb(result); } }; 的速度,尽管可能至少稍慢一些,因为它需要触发和处理N个事件而不是一个事件。

请不要在MS Edge中尝试它:)

  

以前,我使用IDBIndex.getAllKeys(),但此方法的行为似乎已更改为返回对象存储主键而不是索引键。 (但是,我找不到任何文档,也没有在浏览器发行说明中引用该信息……)

如果您使用的是indexeddb-getall-shim,则较早的版本会错误地返回索引键而不是主键。那从来没有在规格中,只是垫片中的错误。自从我写了填充片之后,...如果造成您的困惑,我深表歉意!

答案 1 :(得分:0)

  

如果它返回与@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = this; setContentView(R.layout.activity_main); viewPager = findViewById(R.id.view_pager); tabLayout = findViewById(R.id.tab_layout); ViewPagerAdapter vp_adapter = new ViewPagerAdapter(getSupportFragmentManager(), this); viewPager.setAdapter(vp_adapter); viewPager.setOffscreenPageLimit(2); tabLayout.setupWithViewPager(viewPager); handlePosition(); } 相同的内容,您是否知道为什么会有IDBIndex.getAllKeys()方法

使用这两种方法的一个原因是,它们都接受可选的IDBObjectStore.getAllKeys()参数,这是一个关键范围。

对于query,键范围是主键的范围,结果是主键

的数组

对于IDBObjectStore.getAllKeys(query),键范围是索引键的范围,结果是主键

的数组

示例:

IDBIndex.getAllKeys(query)