queries
SQL, Document, and Graph query styles
ai-database unifies three query paradigms in a single API.
Import
import { DB } from 'ai-database'
const { db } = DB({
Post: { title: 'string', published: 'boolean' },
})Query Styles
| Style | Best For | Example |
|---|---|---|
| SQL | Relational data, comparisons | price: { $gt: 100 } |
| Document | Nested data, arrays | 'profile.city': 'SF' |
| Graph | Relationships, traversal | $rel: { type: 'follows' } |
Basic Queries
// List all
const posts = await db.Post.list()
// Find by criteria
const published = await db.Post.find({
status: 'published',
})
// With options
const recent = await db.Post.list({
where: { published: true },
orderBy: 'createdAt',
order: 'desc',
limit: 10,
})Operators
| Category | Operators |
|---|---|
| Comparison | $eq, $ne, $gt, $gte, $lt, $lte |
| Set | $in, $nin |
| Array | $contains, $containsAll, $size |
| String | $startsWith, $endsWith, $regex |
| Existence | $exists, $type |
| Logical | $and, $or, $not |
| Graph | $rel, $relCount |
SQL-Style
const posts = await db.Post.find({
publishedAt: { $gte: lastWeek },
views: { $gt: 100 },
status: { $in: ['published', 'featured'] },
})Document-Style
const posts = await db.Post.find({
'metadata.wordCount': { $gte: 1000 },
tags: { $containsAll: ['ai', 'tutorial'] },
})Graph-Style
const posts = await db.Post.find({
$rel: {
type: 'authored',
from: {
type: 'User',
where: { verified: true },
},
},
})Combining Styles
Mix all three in a single query:
const posts = await db.Post.find({
// SQL-style: comparisons
publishedAt: { $gte: lastWeek },
// Document-style: nested fields
'metadata.wordCount': { $gte: 1000 },
tags: { $containsAll: ['ai', 'tutorial'] },
// Graph-style: relationships
$rel: {
type: 'authored',
from: {
type: 'User',
where: { verified: true },
},
},
})Search vs Query
Queries filter by exact criteria:
const drafts = await db.Post.find({
status: 'draft',
})Search finds by semantic similarity:
const results = await db.Post.search('AI tutorials for beginners')Combine both:
const results = await db.Post.search({
query: 'AI tutorials',
where: { published: true },
})Was this page helpful?