Skip to main content

Getting DatabaseManager

const db = client.database(); // Uses appId from client config
// or
const db = client.database('specific-app-id');

Indexes

listIndexes

List all indexes for the app.
const indexes = await db.listIndexes();

createIndex

Create an index on a collection.
await db.createIndex(indexDefinition: Index);
interface Index {
  name: string;
  collection: string;
  field_name: string;
  index_type: 'btree' | 'hash' | 'fulltext' | 'composite' | 'price';
  fields?: string[];              // For composite indexes
  store_values?: boolean;
  unique_constraint?: boolean;
  sort_enabled?: boolean;
  price_config?: WriteIndexConfig;       // Write-time payment (price indexes)
  read_price_config?: ReadIndexConfig;   // Read-time payment
  creator_premium_config?: CreatorPremiumConfig; // Creator revenue sharing
}
Examples:
// Hash index for equality lookups
await db.createIndex({
  name: 'idx_users_email',
  collection: 'users',
  field_name: 'email',
  index_type: 'hash',
  unique_constraint: true,
  store_values: true
});

// BTree index for range queries
await db.createIndex({
  name: 'idx_users_createdAt',
  collection: 'users',
  field_name: 'createdAt',
  index_type: 'btree'
});

// Fulltext index for search
await db.createIndex({
  name: 'idx_posts_content',
  collection: 'posts',
  field_name: 'content',
  index_type: 'fulltext'
});

createIndexes

Bulk create indexes for a collection.
await db.createIndexes('users', [
  { name: 'idx_email', field_name: 'email', index_type: 'hash', unique_constraint: true, store_values: true },
  { name: 'idx_created', field_name: 'createdAt', index_type: 'btree', store_values: true }
]);

createWriteIndex

Create a write-priced index. Charges writers a fee on every /store call.
await db.createWriteIndex('posts', 'author', {
  pricing_model: 'per_record',
  price_per_record: 500_000  // 0.50 USDC per write
});

createReadIndex

Create a read-priced index. Charges readers a fee when the index is queried.
await db.createReadIndex('articles', 'content', {
  pricing_model: 'per_access',
  price_per_access: 100_000  // 0.10 USDC per matched record
}, { indexType: 'fulltext' });

createCreatorPremiumIndex

Create a creator-premium index. Routes a portion of write revenue to the content creator.
await db.createCreatorPremiumIndex('tracks', 'title', {
  creator_address_resolution: 'metadata.artist_address',
  creator_cut_model: 'per_value_percent',
  creator_cut_value: 10,          // 10% of the price field
  value_field_name: 'price_usdc'
});

dropIndex

Delete an index by ID.
await db.dropIndex('index-id');

Materialized Views

createView

Create a materialized view using a JSON query definition.
await db.createView(
  'completed_orders',
  ['orders'],
  {
    find: { status: { is: 'completed' } },
    select: { id: true, total: true, customer: true }
  }
);

createViewSql

Create a materialized view using SQL with optional refresh mode.
await db.createViewSql(
  'CREATE VIEW customer_revenue AS SELECT customer, SUM(total) as revenue FROM app::orders GROUP BY customer',
  'live'  // 'live' (auto-refresh) or 'lazy' (manual refresh)
);
// Note: createViewSql takes 2 parameters: (sql, refreshMode?)
// The view name is derived from the SQL statement

queryView

Query data from a materialized view.
const result = await db.queryView<OrderSummary>('completed_orders', {
  find: { total: { greaterThan: 100 } },
  select: { id: true, total: true },
  sort_by: ['total'],
  limit: 50,
  offset: 0
});
// result: { success, view_name, data, count, query_time_ms }

countView

Count records in a view with optional filter.
const count = await db.countView('completed_orders', { total: { greaterThan: 100 } });

listViews

List all views for the app.
const views = await db.listViews();
// views: [{ name, source_collections, created_at }]

getView

Get a specific view definition.
const view = await db.getView('completed_orders');

refreshView

Manually refresh/rebuild view data.
await db.refreshView('completed_orders');

deleteView

Delete a view.
await db.deleteView('completed_orders');

API Collections

API Collections allow you to create collections backed by external APIs.

createApiCollection

await db.createApiCollection({
  name: 'external_users',
  description: 'Users from external API',
  api_config: {
    base_url: 'https://api.example.com',
    authentication: { type: 'bearer', token: '...' },
    query_mapping: { /* ... */ },
    response_mapping: { /* ... */ }
  }
});

listApiCollections / getApiCollection / deleteApiCollection

const collections = await db.listApiCollections();
const collection = await db.getApiCollection('external_users');
await db.deleteApiCollection('external_users');

View with Aggregations

const aggregatedView = {
  find: {},
  select: {},
  group_by: ['category'],
  aggregate: {
    total_sales: { '$sum': 'amount' },
    order_count: { '$count': '*' },
    avg_order: { '$avg': 'amount' }
  },
  sort_by: ['total_sales'],
  limit: 100
};

await db.createView('sales_by_category', ['orders'], aggregatedView);

Aggregation Operators

OperatorDescription
$sumSum values
$avgAverage values
$countCount records
$countDistinctCount unique values
$minMinimum value
$maxMaximum value