IndexedDB Manipulation with Dexie: Understanding Complex Queries
Written on
Chapter 1: Introduction to IndexedDB
IndexedDB provides a robust solution for storing data directly in the browser. It supports larger data sets than local storage and operates asynchronously, making it a powerful tool for web developers. Dexie.js simplifies interactions with IndexedDB, streamlining the process of querying and modifying data.
Section 1.1: Querying and Modifying Data
One of the powerful features of Dexie is its ability to query and modify data simultaneously. Below is an example of how this can be implemented:
(async () => {
const db = new Dexie("friend_database");
try {
await db.version(1).stores({
friends: 'name,age'});
await db.friends.put({ name: "mary", age: 68 });
await db.friends.put({ name: "jane", age: 28 });
await db.friends
.where('age')
.inAnyRange([
[0, 18],
[65, Infinity]
])
.modify({ discount: 0.5 });
} catch (error) {
console.log(error);}
})()
In this code, we retrieve all entries in the friends table where the age is either between 0 and 18 or 65 and above. We then apply a modification to set the discount field to 0.5.
Subsection 1.1.1: Searching for Entries with Custom Conditions
We can also search for entries based on specific conditions using the filter method. For instance:
(async () => {
const db = new Dexie("friend_database");
try {
await db.version(1).stores({
friends: 'name,age'});
await db.friends.put({ name: "mary", age: 68 });
await db.friends.put({ name: "jane", age: 28 });
const someFriends = await db.friends
.filter(friend => /j/i.test(friend.name))
.toArray();
console.log(someFriends);
} catch (error) {
console.log(error);}
})()
In this example, we filter friends based on the presence of the letter "j" in their names.
Section 1.2: Utilizing Compound Indexes
Dexie allows the use of compound indexes for more intricate queries. The following code demonstrates how to search with a compound index:
(async () => {
const db = new Dexie("friend_database");
try {
await db.version(1).stores({
friends: '++id,[firstName+lastName],age'});
await db.friends.put({ firstName: "mary", lastName: 'smith', age: 39 });
await db.friends.put({ firstName: "jane", lastName: 'wong', age: 28 });
const someFriends = await db.friends
.where('[firstName+lastName]')
.equals(["jane", "wong"])
.first();
console.log(someFriends);
} catch (error) {
console.log(error);}
})()
Here, we create a compound index on first and last names, allowing us to query for both attributes together.
Chapter 2: Advanced Query Techniques
Explore how to get started with IndexedDB and Dexie.js in this beginner’s guide.
Learn how to build a simple React application utilizing IndexedDB, Dexie.js, and file uploads.
Conclusion
With Dexie, we can execute complex queries that modify data, search with specific conditions, and leverage compound indexes effectively. This makes it a vital tool for developers working with IndexedDB.