Skip to main content

๐Ÿท๏ธ Indexing

Make your queries lightning-fast! Cascade makes it super easy to define and manage indexes for your collections. ๐Ÿš€

โšก Why Indexes?โ€‹

Indexes help your database find data fasterโ€”think of them as magic bookmarks for your collections!

๐Ÿ—๏ธ Defining Indexesโ€‹

Just add a static indexes property to your model:

src/models/user.ts
import { Model } from "@warlock.js/cascade";

export class User extends Model {
public static collection = "users";
public static indexes = [
{ key: { email: 1 }, unique: true }, // Unique index on email
{ key: { createdAt: -1 } }, // Sort by createdAt descending
];
}

๐Ÿงฉ Compound Indexesโ€‹

Combine multiple fields for even more powerful queries:

src/models/post.ts
public static indexes = [
{ key: { authorId: 1, createdAt: -1 } },
];

โณ TTL (Time-To-Live) Indexesโ€‹

Automatically remove old documents:

src/models/session.ts
public static indexes = [
{ key: { expiresAt: 1 }, expireAfterSeconds: 3600 },
];

๐Ÿง™โ€โ™‚๏ธ Pro Tip: Background Indexesโ€‹

Build indexes in the background so your app stays fast:

src/models/user.ts
public static indexes = [
{ key: { email: 1 }, background: true },
];

โš ๏ธ Best Practicesโ€‹

  • Always index fields you query or sort by often.
  • Use unique indexes for emails, usernames, etc.
  • Don't over-indexโ€”each index uses memory!
info

Indexes are managed automatically when you use migrations. No manual database work needed!


๐ŸŒŸ What's Next?โ€‹