我有这些对象,每个对象都有一个‘tag’数组:
bookmarks: [
{ url: '...', tags: ['news', 'fun', 'programming'] },
{ url: '...', tags: ['news'] },
{ url: '...', tags: ['fun', 'cooking'] },
{ url: '...', tags: ['hobby', 'fun'] }
]数据库:
const db = new Dexie("bookmarksdb");
db.version(1).stores({
bookmarks: 'url, *tags'
});接收包含所有标记的数组(或集合)的最佳(和最高性能)方式是什么:
['news', 'fun', 'programming', 'cooking', 'hobby'](有没有办法获得“标签”索引本身的所有值?)
编辑:要显示带有数字的“标签云”,我需要读取书签表中的所有标签。所以,我不需要书签对象本身,只需要它们的“标签”数组。
发布于 2020-04-22 04:27:30
我建议使用index过滤掉至少包含一个标签的所有书签,然后手动过滤掉:
const tagsToRequire = ['news', 'fun', 'programming', 'cooking', 'hobby'];
const bookmarksWithFirstTag = await db.bookmarks
.where({tags: tagsToRequire[0]})
.toArray();
const bookmarkWithAllTags = bookmarkWithFirstTag.filter(bookmark => tagsToRequire.every(tag => bookmark.tags.includes(tag));你也可以对所有的标签使用索引,但是它不能保证你会得到更好的性能,因为它需要更多的数据库请求。另一方面,在第一个索引非常常用并且对象很大的情况下,第二个示例可能会在性能上做得更好:
const tagsToRequire = ['news', 'fun', 'programming', 'cooking', 'hobby'];
const keys = await Promise.all(tagsToRequire.map(tag =>
db.bookmarks.where({tags: tag}).primaryKeys()));
const intersectedKeys = keys.reduce((prev, curr) => prev.filter(key => curr.includes(key)));
const bookmarkWithAllTags = await db.bookmark.bulkGet(intersectedKeys); 第二个示例还需要具有bulkGet()操作的Dexie版本3.x。
https://stackoverflow.com/questions/61351827
复制相似问题