CRUD
select
查询一条
ts
await db.get("posts", 1)查所有
ts
const list = await db.getAll("user");
// 只取前面10条
const list = await db.getAll('posts', undefined, 10)类 where
ts
// 查一条
const post = await db.getFromIndex( 'posts', 'by-title', 'Hello' )
// SELECT * FROM posts WHERE title = 'Hello' LIMIT 1
// 查多条
const list = await db.getAllFromIndex( 'posts', 'by-title', 'Hello' )
// SELECT * FROM posts WHERE title = 'Hello'
await db.getAllFromIndex('posts', 'by-title', 'Hello', 10)// 10 是 limit范围查询
ts
import { IDBKeyRange } from 'idb'
const range = IDBKeyRange.bound('A', 'M')
await db.getAllFromIndex('posts', 'by-title', range)sql
WHERE title BETWEEN 'A' AND 'M'模糊查询
todo
其他
提示
add:只能新增(重复会报错)
put:新增 or 覆盖(更新)
db.put(storeName, value, key?) 的 key 只有没有 keyPath 的时候才可以使用
ts
const data = { title: "xx" };
const id = await db.add("posts", data);
// 更新
await db.put("auth", {
id,
...data
});删除
ts
await db.delete("posts", 1)1. 索引能加速读,但会拖慢写
2. 索引会占磁盘空间
3. 高重复字段不一定值得建普通索引
4. order by / join / where 常用字段更适合建索引
5. 复合索引讲究字段顺序
6. LIKE '%abc%' 普通索引通常帮不上忙清空表
ts
await db.clear("auth");索引(Index)
我提前给你铺好查询道路,只能沿着这些路查
索引在 indexdb 是 “刚需”。因为查询依赖它。
ts
db.createObjectStore("user", { keyPath: "id" })
.createIndex("by-name", "name");- by-title 是 index name
- name 是数据字段
复合索引
ts
store.createIndex( "by-type-origin", ["type", "origin"] )ts
const list = await db.getAllFromIndex(
"file_resources",
"by-type-origin",
["image", "mock"]
)前缀查询
ts
const range = IDBKeyRange.bound(
["image"],
["image", "\uffff"]
)
const list = await db.getAllFromIndex(
"file_resources",
"by-type-origin",
range
)