# Skirre — AI Migration Rulebook > **Purpose:** This document is a single, comprehensive reference that any AI assistant > can consume to generate correct migration code from **any search platform** to Skirre. > The AI already knows the source platform (Algolia, Meilisearch, Typesense, Elasticsearch, > Shopify, WooCommerce, etc.) — it only needs accurate knowledge of the **target** surface. > > Feed this entire document to your AI assistant alongside your migration request. --- ## Table of Contents 1. [Overview](#1-overview) 2. [SDK Installation & Initialization](#2-sdk-installation--initialization) 3. [Authentication](#3-authentication) 4. [Index Management](#4-index-management) 5. [Field Configuration](#5-field-configuration) 6. [Document Operations](#6-document-operations) 7. [Async Task System](#7-async-task-system) 8. [Search](#8-search) 9. [Filter Syntax](#9-filter-syntax) 10. [Similar Documents](#10-similar-documents) 11. [Index Settings](#11-index-settings) 12. [Aliases (Zero-Downtime Index Swaps)](#12-aliases) 13. [Events & Behavioral Tracking](#13-events--behavioral-tracking) 14. [Analytics](#14-analytics) 15. [Query Suggestions (Autocomplete)](#15-query-suggestions) 16. [Zero-Result Suggestions](#16-zero-result-suggestions) 17. [Auto-Synonym Suggestions](#17-auto-synonym-suggestions) 18. [Scoring (Behavioral Signals)](#18-scoring) 19. [Enrichment (LLM-Powered)](#19-enrichment) 20. [Reindex & Reconcile](#20-reindex--reconcile) 21. [API Keys & Tenant Tokens](#21-api-keys--tenant-tokens) 22. [Error Handling](#22-error-handling) 23. [Rate Limits & Retries](#23-rate-limits--retries) 24. [Client-Side Analytics (Browser SDK)](#24-client-side-analytics) 25. [Migration Mapping Cheatsheets](#25-migration-mapping-cheatsheets) --- ## 1. Overview Skirre is a search-as-a-service platform built on Rust (Axum + Tantivy) with an R2 document store for durability. Key characteristics: - **Multi-tenant**: Every resource is scoped to an account via API key. Index UIDs are unique per account. - **Async writes**: All document mutations and settings updates are enqueued as tasks. The API returns a `TaskInfo` (HTTP 202) immediately. Poll the task endpoint to check completion. - **Generic schema**: Indices have configurable searchable, filterable, and sortable attributes. Documents are schemaless JSON — Skirre indexes the configured fields. - **Hybrid search**: Keyword (BM25 + Tantivy) with optional semantic re-ranking (embeddings via fastembed). - **Built-in analytics**: Search analytics, behavioral events, site analytics, and commerce funnel tracking. **Base URL**: Provided at account creation (e.g. `https://search.example.com`). There is no default. **SDK**: `@skirre/sdk` (npm). Always install the latest version. **Wire format**: All request/response bodies use `snake_case` JSON. --- ## 2. SDK Installation & Initialization ```bash npm install @skirre/sdk # or yarn add @skirre/sdk # or pnpm add @skirre/sdk ``` ```typescript import { Skirre } from '@skirre/sdk'; const skirre = new Skirre({ apiKey: 'sk_admin_live_...', // admin key for write operations baseUrl: 'https://search.example.com', timeout: 30_000, // optional, default 30s maxNetworkRetries: 2, // optional, default 2 }); // Get a handle to an index (no API call, just a wrapper) const index = skirre.index('products'); ``` ### SDK Exports ```typescript // Classes import { Skirre, Index, Analytics } from '@skirre/sdk'; // Errors import { SkirreError, SkirreConnectionError, SkirreAuthenticationError, SkirrePermissionError, SkirreNotFoundError, SkirreRateLimitError, SkirreTaskFailedError, SkirreTaskTimeoutError, } from '@skirre/sdk'; // Types — all available as named type imports import type { SkirreConfig, SearchParams, SearchResponse, Hit, IndexInfo, FieldConfig, CreateIndexParams, /* ...etc */ } from '@skirre/sdk'; ``` --- ## 3. Authentication All requests require a `Bearer` token in the `Authorization` header. ### Key Types | Key Prefix | Type | Permissions | | ------------------- | -------- | ----------------------------------------------------- | | `sk_admin_live_` | Admin | Full CRUD on all endpoints | | `sk_search_live_` | Search | GET on any route + POST `/search` + POST `/events` | Search keys **cannot** create/delete indices, modify documents, change settings, or manage keys. ### Tenant Tokens For multi-tenant storefronts where you need per-user filter restrictions (e.g., a marketplace where each seller sees only their products): ```typescript const { token, expires_at } = await skirre.createToken({ search_rules: { 'products': { filter: 'seller_id = "seller_123"' }, // "*" for wildcard default across all indices }, indices: ['products'], // optional allowlist expires_in: 3600, // seconds (1s–172800, i.e. max 48h) // OR: expires_at: '2025-01-01T00:00:00Z' }); // Client uses the token as a Bearer token for search requests ``` Tenant tokens are HMAC-SHA256 signed with the admin key's `signing_secret` (returned once at key creation). The server verifies the signature and applies the embedded filter restrictions to every search. --- ## 4. Index Management ### Create an Index ```typescript const info = await skirre.createIndex({ uid: 'products', // unique per account, alphanumeric + dash + underscore primary_key: 'id', // optional, default "id" display_name: 'Product Catalog', // optional human-readable name searchable_attributes: [ { name: 'title', weight: 10 }, { name: 'description', weight: 5 }, { name: 'brand', weight: 3 }, { name: 'tags', weight: 2 }, // Per-field language override: { name: 'title_ja', weight: 10, language: 'ja' }, ], filterable_attributes: [ { name: 'category', field_type: 'string' }, { name: 'price', field_type: 'number' }, { name: 'in_stock', field_type: 'boolean' }, { name: 'brand', field_type: 'string' }, { name: 'created_at', field_type: 'string' }, ], sortable_attributes: ['price', 'created_at', 'title'], }); ``` **Response** (`IndexInfo`): ```json { "uid": "products", "primary_key": "id", "display_name": "Product Catalog", "number_of_documents": 0, "field_config": { "primary_key": "id", "searchable_attributes": [...], "filterable_attributes": [...], "sortable_attributes": [...] }, "created_at": "2025-01-15T10:30:00Z", "updated_at": "2025-01-15T10:30:00Z" } ``` ### List All Indices ```typescript const indices: IndexInfo[] = await skirre.listIndices(); ``` ### Get a Single Index ```typescript const info: IndexInfo = await skirre.getIndex('products'); ``` ### Delete an Index ```typescript const taskInfo = await skirre.deleteIndex('products'); // Returns TaskInfo — deletion is async ``` ### Get Index Info (from handle) ```typescript const index = skirre.index('products'); const info: IndexInfo = await index.getInfo(); // Same as skirre.getIndex('products') but called from an existing index handle ``` ### Health Check ```typescript const isHealthy: boolean = await skirre.health(); // Returns true if the Skirre instance is reachable, false otherwise ``` ### REST Equivalents | Operation | Method | Path | |-----------|--------|------| | Create | `POST /v1/indices` | Body: `CreateIndexParams` | | List | `GET /v1/indices` | Response: `{ results: IndexInfo[] }` | | Get | `GET /v1/indices/{uid}` | Response: `IndexInfo` | | Delete | `DELETE /v1/indices/{uid}` | Response: `TaskInfo` (202) | --- ## 5. Field Configuration When creating an index, you configure which document fields Skirre should index and how. ### Searchable Attributes Fields that participate in full-text search. Higher `weight` = more influence on relevance ranking. ```typescript interface SearchableField { name: string; // field name in the document JSON weight?: number; // relevance weight (default: 1). Higher = more important. language?: string; // per-field language override (e.g. "ja", "fr") } ``` **Supported languages**: `en`, `es`, `fr`, `de`, `pt`, `it`, `nl`, `ja`, `zh`, `ko` CJK languages (`ja`, `zh`, `ko`) use the Lindera tokenizer for proper word segmentation. European languages use Tantivy's built-in stemmers. ### Filterable Attributes Fields that can be used in filter expressions (equality, comparison, IN). ```typescript interface FilterableField { name: string; field_type?: string; // "string" | "number" | "boolean" (default: "string") } ``` ### Sortable Attributes Field names that can be used in sort expressions. Must be an array of strings. ```typescript sortable_attributes: ['price', 'created_at', 'title'] ``` ### Stored Attributes `stored_attributes` controls which fields are returned in search hits. When set, only those fields appear in the hit document. When omitted (the default), all document fields are returned. > **Note:** `stored_attributes` is not settable via the `createIndex()` call or the SDK currently. It appears in the `FieldConfig` response type as a read-only field. All document fields are returned by default. Use `attributes_to_retrieve` in search params to limit fields per query instead. ### Primary Key The field used to uniquely identify documents. Default: `"id"`. Must be present in every document. Used for upserts (add or replace by primary key). --- ## 6. Document Operations All document write operations are **async** — they return a `TaskInfo` immediately. Use the `*AndWait` SDK methods to block until the task completes. ### Add or Replace Documents (Upsert) ```typescript const index = skirre.index('products'); // Async — returns immediately with TaskInfo const taskInfo = await index.addDocuments([ { id: 'prod_001', title: 'Wireless Headphones', description: 'Premium noise-canceling wireless headphones', price: 299.99, category: 'Electronics', brand: 'AudioTech', in_stock: true, tags: ['wireless', 'noise-canceling', 'bluetooth'], image_url: 'https://cdn.example.com/headphones.jpg', created_at: '2025-01-15T10:00:00Z', }, // ... more documents ]); // OR: block until complete const task = await index.addDocumentsAndWait([...documents], { timeout: 300_000, // 5 minutes (default) initialInterval: 50, // ms between first polls (default) maxInterval: 5_000, // max polling interval (default) }); ``` **Documents are schemaless JSON objects.** Any field not in the field config is stored but not indexed. The primary key field (default `"id"`) must be present and unique. **Batch size**: Send up to thousands of documents per call. The server handles batching internally. ### Partially Update Documents (Merge) Only updates the fields you provide. Other fields on the existing document are preserved. ```typescript // Updates only price and in_stock, leaves title/description/etc unchanged const taskInfo = await index.updateDocuments([ { id: 'prod_001', price: 249.99, in_stock: false }, ]); // OR wait: const task = await index.updateDocumentsAndWait([...]); ``` ### List Documents ```typescript const { results, total, limit, offset } = await index.getDocuments({ limit: 20, // default 20 offset: 0, // default 0 }); ``` ### Get a Single Document ```typescript const doc = await index.getDocument('prod_001'); // Returns: Record ``` ### Delete a Single Document ```typescript const taskInfo = await index.deleteDocument('prod_001'); // OR: const task = await index.deleteDocumentAndWait('prod_001'); ``` ### Delete a Batch of Documents by ID ```typescript const taskInfo = await index.deleteBatch({ ids: ['prod_001', 'prod_002', 'prod_003'] }); // OR: const task = await index.deleteBatchAndWait({ ids: [...] }); ``` ### Delete Documents by Filter ```typescript const taskInfo = await index.deleteByFilter({ filter: 'category = "Deprecated"' }); // OR: const task = await index.deleteByFilterAndWait({ filter: 'price < 0' }); ``` ### REST Equivalents | Operation | Method | Path | Body | |-----------|--------|------|------| | Add/Replace | `POST /v1/indices/{uid}/documents` | JSON array of documents | | Partial Update | `PATCH /v1/indices/{uid}/documents` | JSON array of partial documents | | List | `GET /v1/indices/{uid}/documents?limit=20&offset=0` | — | | Get one | `GET /v1/indices/{uid}/documents/{id}` | — | | Delete one | `DELETE /v1/indices/{uid}/documents/{id}` | — | | Delete batch | `POST /v1/indices/{uid}/documents/delete-batch` | `{ "ids": [...] }` | | Delete by filter | `POST /v1/indices/{uid}/documents/delete-by-filter` | `{ "filter": "..." }` | All write operations return HTTP **202** with `TaskInfo`. --- ## 7. Async Task System Write operations (document add/update/delete, settings update, index deletion, reindex, reconcile) return a `TaskInfo` immediately and execute asynchronously via a NATS JetStream task queue. ### TaskInfo (Immediate Response) ```json { "task_uid": 42, "index_uid": "products", "status": "enqueued", "type": "documentAdditionOrUpdate", "enqueued_at": "2025-01-15T10:30:00Z" } ``` ### Task (Full Record) ```json { "uid": 42, "index_uid": "products", "status": "succeeded", "type": "documentAdditionOrUpdate", "details": { "received_documents": 150, "indexed_documents": 150 }, "enqueued_at": "2025-01-15T10:30:00Z", "started_at": "2025-01-15T10:30:01Z", "finished_at": "2025-01-15T10:30:03Z", "duration_ms": 2000 } ``` ### Task Statuses | Status | Meaning | |--------|---------| | `enqueued` | Waiting in queue | | `processing` | Currently executing | | `succeeded` | Completed successfully | | `failed` | Failed (check `error` field) | | `canceled` | Canceled via cancel endpoint | ### Task Types | Type | Triggered By | |------|--------------| | `documentAdditionOrUpdate` | `POST` documents | | `documentPartialUpdate` | `PATCH` documents | | `documentDeletion` | `DELETE` single document | | `documentDeletionBatch` | `POST` delete-batch | | `documentDeletionByFilter` | `POST` delete-by-filter | | `settingsUpdate` | `PUT` settings | | `indexDeletion` | `DELETE` index | | `indexReindex` | `POST` reindex | | `indexReconcile` | `POST` reconcile | ### SDK Methods ```typescript // Get a single task const task = await skirre.getTask(42); // List tasks with filters const { results, total, limit, from, next } = await skirre.listTasks({ statuses: 'succeeded,failed', types: 'documentAdditionOrUpdate', indexUids: 'products', limit: 50, from: 100, // pagination cursor (task UID, descending) }); // Cancel enqueued tasks const { canceled } = await skirre.cancelTasks({ statuses: 'enqueued', indexUids: 'products', }); // Delete terminal (succeeded/failed/canceled) tasks const { deleted } = await skirre.deleteTasks({ statuses: 'succeeded', beforeEnqueuedAt: '2025-01-01T00:00:00Z', }); // Wait for a task to complete (blocks with polling) const completedTask = await skirre.waitForTask(42, { timeout: 300_000, // max wait time in ms (default: 5 min) initialInterval: 50, // first polling interval in ms maxInterval: 5_000, // max polling interval in ms (exponential backoff) }); // Throws SkirreTaskFailedError if task fails // Throws SkirreTaskTimeoutError if timeout exceeded ``` ### REST Equivalents | Operation | Method | Path | |-----------|--------|------| | List | `GET /v1/tasks` | Query params: uids, indexUids, statuses, types, limit, from, beforeEnqueuedAt, afterEnqueuedAt, beforeStartedAt, afterStartedAt, beforeFinishedAt, afterFinishedAt, canceledBy | | Get | `GET /v1/tasks/{uid}` | | | Cancel | `POST /v1/tasks/cancel` | Query params same as list | | Delete | `POST /v1/tasks/delete` | Query params same as list | --- ## 8. Search ### Basic Search ```typescript const index = skirre.index('products'); const results = await index.search('wireless headphones', { limit: 20, offset: 0, }); ``` ### Full Search Parameters ```typescript interface SearchParams { filter?: string; // filter expression (see Filter Syntax) sort?: string[]; // e.g. ['price:asc', 'created_at:desc'] limit?: number; // max results (default varies) offset?: number; // pagination offset (default 0) facets?: string[]; // filterable fields to compute facet counts attributes_to_retrieve?: string[]; // limit which fields appear in _source show_ranking_score?: boolean; // include relevance score per hit show_timing?: boolean; // include per-stage timing breakdown show_profile?: boolean; // include diagnostic profile (implies show_timing) session_id?: string; // for analytics session stitching (auto-set by SDK) } ``` ### Search Response ```typescript interface SearchResponse { hits: Hit[]; facet_distribution?: Record>; total_hits: number; processing_time_ms: number; limit: number; offset: number; query: string; query_id: string; // unique ID for event attribution timing?: TimingBreakdown; // when show_timing is set profile?: SearchProfile; // when show_profile is set } // Each hit is the flat stored document (Record). // The primary key field (default "id") is always present. // When show_ranking_score is true, a `_rankingScore: number` field is injected. // // Example hit: // { // "id": "prod_001", // "title": "Wireless Headphones", // "price": 299.99, // "category": "Electronics", // "_rankingScore": 0.87 // only when show_ranking_score: true // } ``` ### Search with Filters, Facets, and Sort ```typescript const results = await index.search('headphones', { filter: 'category = "Electronics" AND price >= 100 AND price <= 500 AND in_stock = true', sort: ['price:asc'], facets: ['category', 'brand'], attributes_to_retrieve: ['id', 'title', 'price', 'image_url'], limit: 20, offset: 0, }); // results.facet_distribution: // { // "category": { "Electronics": 45, "Audio": 12 }, // "brand": { "AudioTech": 8, "SoundMax": 5 } // } ``` ### Empty Query (Browse All) ```typescript // Pass empty string or omit query to return all documents (useful for category pages) const results = await index.search('', { filter: 'category = "Electronics"', sort: ['created_at:desc'], }); ``` ### Diagnostic Profile ```typescript const results = await index.search('wireless', { show_profile: true }); // results.profile: // { // query_analysis: { // original_query: "wireless", // tokens: [{ raw: "wireless", stemmed: "wireless", synonyms: [], fuzzy_distance: 0, prefix_eligible: true }], // language: "en", // tokenizer: "default" // }, // query_tree: "OR(Term(\"wireless\"), Prefix(\"wireless\"))", // filters_applied: [], // rerank: { mode: "hybrid", quantization: "none", candidates_fetched: 100, ... }, // index_stats: { total_documents: 1500, segments: 3, language: "en" } // } ``` ### REST Equivalent ``` POST /v1/indices/{uid}/search Content-Type: application/json Authorization: Bearer sk_search_live_... { "q": "wireless headphones", "filter": "category = \"Electronics\"", "sort": ["price:asc"], "facets": ["category", "brand"], "attributes_to_retrieve": ["id", "title", "price"], "limit": 20, "offset": 0, "show_ranking_score": true } ``` --- ## 9. Filter Syntax Skirre uses a string-based filter syntax. Only fields declared as `filterable_attributes` can be used. ### Operators | Operator | Example | Notes | |----------|---------|-------| | `=` | `category = "Electronics"` | Exact match (string) | | `!=` | `brand != "Generic"` | Not equal | | `>` | `price > 100` | Greater than (number) | | `>=` | `price >= 100` | Greater or equal | | `<` | `price < 500` | Less than | | `<=` | `price <= 500` | Less or equal | | `IN` | `category IN ["Electronics", "Audio"]` | Array containment | | `NOT IN` | `brand NOT IN ["Generic", "Unknown"]` | Array exclusion | | `EXISTS` | `brand EXISTS` | Field is present and non-null | | `NOT EXISTS` | `discount NOT EXISTS` | Field is missing or null | | `IS NULL` | `brand IS NULL` | Field is null | | `IS NOT NULL` | `brand IS NOT NULL` | Field is not null | | `TO` | `price 100 TO 500` | Range (inclusive) | ### Boolean Combinators | Combinator | Example | |------------|---------| | `AND` | `category = "Electronics" AND price > 100` | | `OR` | `brand = "AudioTech" OR brand = "SoundMax"` | | `NOT` | `NOT category = "Deprecated"` | | `()` | `(brand = "A" OR brand = "B") AND price < 100` | ### Complete Example ``` category = "Electronics" AND price >= 50 AND price <= 300 AND in_stock = true AND brand IN ["AudioTech", "SoundMax"] ``` ### Important Notes - String values must be quoted with double quotes: `category = "Electronics"` - Number values are unquoted: `price > 100` - Boolean values: `in_stock = true` or `in_stock = false` - The filter field must be declared in `filterable_attributes` at index creation time - Nested field access is via dot notation if the field was declared that way --- ## 10. Similar Documents Find documents similar to a given document using embedding cosine similarity. Requires semantic search to be enabled in settings. ```typescript const results = await index.similar('prod_001', { limit: 10, offset: 0, filter: 'in_stock = true', // optional, same syntax as search attributes_to_retrieve: ['id', 'title'], // optional show_ranking_score: true, // include similarity score }); ``` ### Response ```typescript interface SimilarResponse { hits: Record[]; // flat documents, like search hits total_hits: number; processing_time_ms: number; limit: number; offset: number; document_id: string; // the source document ID } // When show_ranking_score is true, each hit includes `_similarityScore: number` // (cosine similarity) instead of search's `_rankingScore`. ``` ### REST Equivalent ``` POST /v1/indices/{uid}/similar { "document_id": "prod_001", "limit": 10, "filter": "in_stock = true", "show_ranking_score": true } ``` --- ## 11. Index Settings Settings control search behavior: synonyms, typo tolerance, semantic search, scoring, enrichment, and more. ### Get Settings ```typescript const settings = await index.getSettings(); ``` ### Update Settings Settings updates are **async** (return `TaskInfo`). ```typescript // Async const taskInfo = await index.updateSettings({ language: 'en', synonyms: { 'headphones': ['earphones', 'earbuds'], 'tv': ['television', 'monitor'], 'laptop': ['notebook'], }, attribute_weights: { 'title': 10, 'description': 5, 'brand': 3, }, typo_tolerance: { enabled: true, min_word_length_1_typo: 4, // words ≥4 chars allow 1 typo min_word_length_2_typos: 8, // words ≥8 chars allow 2 typos }, price_ranges: [ { label: 'Under $25', min: 0, max: 25 }, { label: '$25–$50', min: 25, max: 50 }, { label: '$50–$100', min: 50, max: 100 }, { label: 'Over $100', min: 100, max: 999999 }, ], semantic: { enabled: true, keyword_weight: 0.7, // BM25 text relevance weight semantic_weight: 0.3, // embedding cosine similarity weight quantization: 'none', // 'none' | 'binary' | 'binary+rescore' }, scoring: { enabled: true, weights: { sales_count: 0.30, revenue: 0.20, ctr: 0.20, conversion_rate: 0.15, view_count: 0.10, recency: 0.05, }, ranking_weight: 0.15, // how much composite score influences search ranking (0–0.5) }, enrichment: { enabled: false, mode: 'suggest', // 'suggest' | 'auto_apply' confidence_threshold: 0.8, batch_size: 50, categories: ['Electronics', 'Clothing', 'Home'], provider: { base_url: 'https://api.openai.com/v1', api_key: 'sk-...', model: 'gpt-4o-mini', max_tokens: 1000, }, }, }); // OR wait: const task = await index.updateSettingsAndWait({ ... }); ``` ### Complete Settings Schema ```typescript interface IndexSettings { language: string; // tokenization language (e.g. "en", "fr", "ja") synonyms: Record; // one-way synonym mappings attribute_weights: Record; // per-field relevance multipliers typo_tolerance: TypoTolerance; price_ranges: PriceRange[]; // facet-friendly price buckets semantic: SemanticSettings; enrichment: EnrichmentSettings; scoring: ScoringSettings; } interface TypoTolerance { enabled: boolean; min_word_length_1_typo: number; // min chars to allow 1 typo (default: 5) min_word_length_2_typos: number; // min chars to allow 2 typos (default: 9) } interface SemanticSettings { enabled: boolean; keyword_weight: number; // 0.0–1.0, weight for BM25 text scoring semantic_weight: number; // 0.0–1.0, weight for embedding cosine similarity quantization?: 'none' | 'binary' | 'binary+rescore'; // vector storage mode } interface ScoringSettings { enabled: boolean; weights: ScoringWeights; // per-signal weights for composite score ranking_weight: number; // how much composite score influences search (0.0–0.5) } interface ScoringWeights { sales_count: number; // default 0.30 revenue: number; // default 0.20 ctr: number; // default 0.20 conversion_rate: number; // default 0.15 view_count: number; // default 0.10 recency: number; // default 0.05 } interface PriceRange { label: string; min: number; max: number; } interface EnrichmentSettings { enabled: boolean; provider?: LlmProvider; mode: 'suggest' | 'auto_apply'; confidence_threshold: number; // 0.0–1.0 batch_size: number; categories: string[]; // category labels for enrichment prompts } interface LlmProvider { base_url: string; // e.g. 'https://api.openai.com/v1' api_key: string; model: string; // e.g. 'gpt-4o-mini' max_tokens: number; } ``` ### REST Equivalents | Operation | Method | Path | |-----------|--------|------| | Get | `GET /v1/indices/{uid}/settings` | Response: `IndexSettings` | | Update | `PUT /v1/indices/{uid}/settings` | Body: partial `UpdateSettingsParams`, Response: `TaskInfo` (202) | **Note**: Changing the `language` setting requires a full reindex. --- ## 12. Aliases Aliases are named pointers to indices, enabling zero-downtime index swaps (e.g., build a new index, then atomically switch the alias). ### Atomic Batch Set ```typescript // Set multiple aliases atomically (replaces any existing mappings for these names) const aliases = await skirre.setAliases({ aliases: { 'products': 'products_v2', // alias "products" → index "products_v2" 'blog': 'blog_20250115', }, }); ``` ### List Aliases ```typescript const aliases: AliasInfo[] = await skirre.listAliases(); // [{ alias_name: "products", target_index_uid: "products_v2", created_at: ..., updated_at: ... }] ``` ### Delete an Alias ```typescript await skirre.deleteAlias('products'); ``` ### Rules - Alias names: alphanumeric + dash + underscore, 1–128 characters - No chaining: an alias cannot point to another alias - Search requests can use alias names in place of index UIDs ### REST Equivalents | Operation | Method | Path | |-----------|--------|------| | Set (batch) | `PUT /v1/aliases` | Body: `{ "aliases": { "name": "index_uid" } }` | | List | `GET /v1/aliases` | Response: `{ "results": AliasInfo[] }` | | Delete | `DELETE /v1/aliases/{name}` | 204 No Content | --- ## 13. Events & Behavioral Tracking Skirre tracks behavioral events for analytics, scoring, and search personalization. ### Event Types | Type | Purpose | Required Fields | |------|---------|-----------------| | `click` | User clicked a search result | `index_uid`, `document_id` | | `add_to_cart` | User added item to cart | `index_uid`, `document_id` | | `purchase` | User purchased item | `index_uid`, `document_id` | | `conversion` | Generic conversion event | `index_uid`, `document_id` | | `view` | User viewed a document/product | `index_uid`, `document_id` | | `page_view` | User visited a page | `url` | ### Send Events ```typescript await skirre.sendEvents({ events: [ { type: 'click', index_uid: 'products', document_id: 'prod_001', query_id: 'qry_abc123', // from search response, for attribution session_id: 'sess_xyz', // auto-set by SDK in browser position: 0, // 0-indexed position in search results }, { type: 'purchase', index_uid: 'products', document_id: 'prod_001', metadata: { revenue: 299.99, quantity: 1, currency: 'USD', }, }, { type: 'page_view', url: '/products/wireless-headphones', referrer: 'https://google.com', session_id: 'sess_xyz', }, ], }); ``` ### Event Schema ```typescript interface BehavioralEvent { type: string; // "click" | "add_to_cart" | "purchase" | "conversion" | "view" | "page_view" index_uid?: string; // required for behavioral events, omit for page_view document_id?: string; // required for behavioral events, omit for page_view query_id?: string; // from SearchResponse.query_id — enables attribution session_id?: string; // client-generated session ID position?: number; // 0-indexed result position timestamp?: string; // ISO 8601 (server time if omitted) metadata?: Record; // arbitrary data (revenue, quantity, etc.) url?: string; // page URL (for page_view) referrer?: string; // referrer URL (for page_view) } ``` ### REST Equivalent ``` POST /v1/events Authorization: Bearer sk_search_live_... (search keys can send events) { "events": [...] } ``` **Max batch size**: 1000 events per request. **Server-side enrichment**: The server automatically extracts GeoIP data (country) and User-Agent details (browser, device, OS) from the request headers. --- ## 14. Analytics ### Per-Index Analytics #### Top Queries ```typescript const topQueries = await index.getTopQueries({ days: 7, limit: 20 }); // [{ query: "headphones", count: 150, avg_hits: 45 }] ``` #### No-Result Queries ```typescript const noResults = await index.getNoResultQueries({ days: 7, limit: 20 }); // [{ query: "airpodz", count: 12, last_searched: "2025-01-15T10:30:00Z" }] ``` #### Event Analytics (per-index) ```typescript const eventAnalytics = await index.getEventAnalytics({ event_type: 'click', // "view" | "click" | "purchase" | "add_to_cart" | "conversion" days: 7, // 1 | 7 | 14 | 30 | 90 limit: 20, // top documents to return granularity: 'day', // "hour" | "day" }); // { // summary: { total: 500, unique_documents: 120 }, // top_documents: [{ document_id: "prod_001", count: 45 }, ...], // timeseries: [{ timestamp: "2025-01-15T00:00:00Z", count: 72 }, ...] // } ``` #### Delete All Analytics for an Index Clears all analytics data (search queries, behavioral events, suggestions, scores) for an index. ```typescript const { deleted } = await index.deleteAnalytics(); // deleted: { // search_queries: 1500, // behavioral_events: 3200, // query_suggestions: 50, // document_scores: 150, // zero_result_suggestions: 12, // auto_synonym_suggestions: 8 // } ``` ```typescript interface DeleteAnalyticsResult { search_queries: number; behavioral_events: number; query_suggestions: number; document_scores: number; zero_result_suggestions: number; auto_synonym_suggestions: number; } ``` ### Account-Level Analytics #### Timeseries (Search Volume) ```typescript const timeseries = await skirre.getTimeseries({ period: '7d', // "24h" | "7d" | "30d" granularity: 'day', // "hour" | "day" (auto if omitted) index_uid: 'products', // optional, filter to one index }); // { // buckets: [{ timestamp: "...", queries: 150, avg_latency_ms: 12, no_result_count: 5 }], // summary: { total_queries: 1200, avg_latency_ms: 14, no_result_rate: 0.04, queries_trend: 0.12 } // } ``` #### Site Analytics ```typescript const site = await skirre.getSiteAnalytics({ period: '7d', granularity: 'day', limit: 20, }); // { // summary: { total_page_views: 5000, unique_sessions: 1200, search_sessions: 400, search_rate: 0.33, avg_pages_per_session: 4.2 }, // page_views_timeseries: [{ timestamp: "...", views: 720 }], // top_pages: [{ url: "/products", views: 800 }], // top_referrers: [{ referrer: "google.com", sessions: 300 }], // top_countries: [{ country_code: "US", sessions: 500, page_views: 2000 }], // top_browsers: [{ browser: "Chrome", sessions: 600, page_views: 2500 }], // top_devices: [{ device_type: "desktop", sessions: 700, page_views: 3000 }], // top_os: [{ os_name: "Windows", sessions: 400, page_views: 1500 }] // } ``` #### Search Funnel ```typescript const funnel = await skirre.getSearchFunnel({ period: '7d', limit: 10 }); // { // funnel: { searched: 400, clicked_result: 280, added_to_cart: 60, purchased: 25 }, // click_through_rate: 0.70, // search_conversion_rate: 0.0625, // revenue_from_search: 12500.00, // top_converting_queries: [{ query: "headphones", searches: 50, purchases: 8, revenue: 2400 }], // top_exit_queries: [{ query: "airpodz", searches: 12, exits: 12 }] // } ``` #### Search Origins ```typescript const origins = await skirre.getSearchOrigins({ period: '7d', limit: 20 }); // { origins: [{ url: "/", searches: 200, pct: 0.50 }, { url: "/products", searches: 100, pct: 0.25 }] } ``` ### REST Equivalents | Operation | Method | Path | |-----------|--------|------| | Top queries | `GET /v1/indices/{uid}/analytics/top-queries` | | No-result queries | `GET /v1/indices/{uid}/analytics/no-result-queries` | | Event analytics | `GET /v1/indices/{uid}/analytics/events` | | Delete all analytics | `DELETE /v1/indices/{uid}/analytics` | | Timeseries | `GET /v1/analytics/timeseries` | | Site analytics | `GET /v1/analytics/site` | | Search funnel | `GET /v1/analytics/search-funnel` | | Search origins | `GET /v1/analytics/search-origins` | --- ## 15. Query Suggestions Autocomplete / typeahead suggestions based on analytics data and catalog content. ```typescript const { suggestions, source } = await index.suggestions({ q: 'head', // prefix to match limit: 10, // max 20 }); // suggestions: [{ query: "headphones", score: 0.95, result_count: 45 }, ...] // source: "analytics" | "catalog" | "seed" ``` ### REST Equivalent ``` GET /v1/indices/{uid}/suggestions?q=head&limit=10 ``` --- ## 16. Zero-Result Suggestions Skirre automatically identifies queries that return zero results and suggests similar queries that do return results (using embedding similarity). ### List Zero-Result Suggestions ```typescript const suggestions = await index.getZeroResultSuggestions({ status: 'pending', // "pending" | "applied" | "dismissed" limit: 50, }); // [ // { // id: 1, // zero_result_query: "airpodz", // zero_result_count: 12, // suggested_query: "airpods", // suggested_query_hits: 5, // similarity: 0.92, // status: "pending", // created_at: "..." // } // ] ``` ### Apply (Auto-Creates Synonym) ```typescript const result = await index.applyZeroResultSuggestion(1); // { id: 1, status: "applied", synonym_added: { key: "airpodz", values: ["airpods"] } } ``` ### Dismiss ```typescript const result = await index.dismissZeroResultSuggestion(1); // { id: 1, status: "dismissed" } ``` ### Batch Resolve ```typescript const { resolved } = await index.batchResolveZeroResultSuggestions({ ids: [1, 2, 3], action: 'applied', // "applied" | "dismissed" }); ``` --- ## 17. Auto-Synonym Suggestions Skirre analyzes corpus embeddings to find terms that are semantically similar and suggests bidirectional synonym mappings. ### List Suggestions ```typescript const suggestions = await index.getAutoSynonymSuggestions({ status: 'pending', limit: 50, }); // [ // { // id: 1, // term_a: "laptop", // term_a_count: 200, // term_b: "notebook", // term_b_count: 50, // similarity: 0.89, // status: "pending", // created_at: "..." // } // ] ``` ### Apply (Creates Bidirectional Synonyms) ```typescript const result = await index.applyAutoSynonymSuggestion(1); // { id: 1, status: "applied", synonyms_added: [{ key: "laptop", values: ["notebook"] }, { key: "notebook", values: ["laptop"] }] } ``` ### Dismiss / Batch Resolve ```typescript const result = await index.dismissAutoSynonymSuggestion(1); // { id: 1, status: "dismissed" } const { resolved } = await index.batchResolveAutoSynonymSuggestions({ ids: [1, 2, 3], action: 'dismissed', }); ``` --- ## 18. Scoring Skirre computes composite document scores from behavioral signals (events). These scores influence search ranking when enabled. ### Get Scoring Overview ```typescript const { settings, stats } = await index.getScoring(); // settings: { enabled: true, weights: { sales_count: 0.30, ... }, ranking_weight: 0.15 } // stats: { total_scored: 150, average_score: 0.42, last_computed_at: "..." } ``` ### Get Top Scored Documents ```typescript const documents = await index.getTopScores({ limit: 20, offset: 0 }); // [{ document_id: "prod_001", sales_count: 45, revenue: 13500, ctr: 0.12, ..., composite_score: 0.87 }] ``` ### Get Score for a Single Document ```typescript const score = await index.getDocumentScore('prod_001'); // { document_id: "prod_001", sales_count: 45, revenue: 13500, ctr: 0.12, conversion_rate: 0.08, view_count: 300, recency: 0.95, composite_score: 0.87, computed_at: "..." } ``` ### Trigger Recomputation ```typescript const { status, documents_scored } = await index.recomputeScores(); ``` ### Score Breakdown Fields | Signal | Description | Default Weight | |--------|-------------|---------------| | `sales_count` | Purchases in last 30 days | 0.30 | | `revenue` | Total revenue in last 30 days | 0.20 | | `ctr` | Click-through rate in last 30 days | 0.20 | | `conversion_rate` | Purchase-to-click ratio | 0.15 | | `view_count` | Views in last 7 days | 0.10 | | `recency` | Document freshness | 0.05 | --- ## 19. Enrichment LLM-powered catalog enrichment analyzes documents and generates suggestions for tags, categories, attributes, and search terms. ### Enable Enrichment (via Settings) ```typescript await index.updateSettingsAndWait({ enrichment: { enabled: true, provider: { base_url: 'https://api.openai.com/v1', api_key: 'sk-...', model: 'gpt-4o-mini', max_tokens: 1000, }, mode: 'suggest', // "suggest" = human review, "auto_apply" = automatic confidence_threshold: 0.8, batch_size: 50, categories: ['Electronics', 'Clothing', 'Home & Garden'], }, }); ``` ### Run Enrichment Job ```typescript const { job_id, status, total_docs } = await index.runEnrichment({ batch_size: 100, // optional override }); ``` ### Monitor Job Progress ```typescript const jobs = await index.getEnrichmentJobs(); // [{ id: "enr_job_...", status: "running", total_docs: 100, processed_docs: 45, suggestions_count: 120, ... }] const job = await index.getEnrichmentJob('enr_job_...'); ``` ### Review & Apply Suggestions ```typescript const { suggestions, total } = await index.getEnrichmentSuggestions({ status: 'pending', suggestion_type: 'tags', // "tags" | "category" | "attributes" | "search_terms" | "quality" document_id: 'prod_001', // optional filter limit: 50, offset: 0, }); // Apply a suggestion (merges into the document) await index.applyEnrichmentSuggestion('enr_sug_...'); // Dismiss without applying await index.dismissEnrichmentSuggestion('enr_sug_...'); // Batch resolve (max 100 per call) await index.batchResolveEnrichmentSuggestions({ ids: ['enr_sug_001', 'enr_sug_002'], action: 'applied', }); ``` ### Suggestion Types | Type | What It Suggests | Applied Field | |------|-----------------|---------------| | `tags` | Descriptive tags | `_enrichment_tags` (array) | | `category` | Product category | `_enrichment_category` (string) | | `attributes` | Key-value attributes | `_enrichment_attributes` (object) | | `search_terms` | Additional search terms | `_enrichment_search_terms` (array) | | `quality` | Quality score + issues (informational only) | `_enrichment_quality_score`, `_enrichment_quality_issues` | --- ## 20. Reindex & Reconcile ### Reindex Rebuild an index from a source. The target index must already exist and be empty. ```typescript // Copy from another index const taskInfo = await index.reindex({ source_index_uid: 'products_v1' }); // Rebuild from the R2 document store (source of truth) const taskInfo = await index.reindex({ source: 'r2' }); // OR wait: const task = await index.reindexAndWait({ source: 'r2' }); ``` ### Reconcile Detect and fix drift between the document store (R2) and the Tantivy index. - Documents in R2 but missing from Tantivy are re-indexed - Documents in Tantivy but missing from R2 are re-stored from Tantivy's `_source` field ```typescript const taskInfo = await index.reconcile(); // OR: const task = await index.reconcileAndWait(); ``` Requires a document store backend (not `"none"`). --- ## 21. API Keys & Tenant Tokens ### Create an API Key ```typescript const { key, signing_secret, id, name, prefix, key_type, created_at } = await skirre.createKey({ name: 'Production Search Key', key_type: 'search', // "admin" | "search" (default: "search") allowed_origins: 'https://example.com,https://shop.example.com', // optional CORS }); // key: "sk_search_live_..." — shown ONCE // signing_secret: "a1b2c3..." — hex-encoded 32-byte HMAC secret, shown ONCE ``` ### List Keys ```typescript const keys: KeyInfo[] = await skirre.listKeys(); // [{ id: "...", name: "Production Search Key", prefix: "sk_search_live_abc", key_type: "search", rate_limit_per_minute: 60, created_at: "...", last_used_at: "..." }] ``` ### Revoke a Key ```typescript await skirre.revokeKey('key_id'); ``` ### Create Tenant Token ```typescript const { token, expires_at } = await skirre.createToken({ search_rules: { 'products': { filter: 'seller_id = "seller_123"' }, '*': { filter: 'published = true' }, // wildcard default for all indices }, indices: ['products', 'blog'], // optional allowlist expires_in: 3600, // 1 hour (1–172800 seconds, max 48h) }); ``` ### REST Equivalents | Operation | Method | Path | |-----------|--------|------| | Create key | `POST /v1/keys` | Response includes `key` and `signing_secret` (once only) | | List keys | `GET /v1/keys` | Response: `{ "data": KeyInfo[] }` | | Revoke key | `DELETE /v1/keys/{id}` | 204 No Content | | Create token | `POST /v1/tokens` | Response: `{ "token": "...", "expires_at": "..." }` | --- ## 22. Error Handling ### Error Response Shape ```json { "error": { "code": "not_found", "message": "Index 'nonexistent' not found" } } ``` ### HTTP Status Codes | Status | Error Class (SDK) | Code | Meaning | |--------|-------------------|------|---------| | 400 | `SkirreError` | `bad_request` | Invalid request body or parameters | | 401 | `SkirreAuthenticationError` | `unauthorized` | Missing or invalid API key | | 401 | `SkirreError` | `token_expired` | Tenant token expired | | 403 | `SkirrePermissionError` | `forbidden` | Valid key but insufficient permissions | | 404 | `SkirreNotFoundError` | `not_found` | Resource does not exist | | 409 | `SkirreError` | `conflict` | Resource already exists or concurrent conflict | | 429 | `SkirreRateLimitError` | `rate_limited` | Too many requests (check `Retry-After` header) | | 500 | `SkirreError` | `internal` | Server error | ### SDK Error Hierarchy ``` SkirreError (base) ├── SkirreConnectionError — network failure, timeout, no HTTP response ├── SkirreAuthenticationError — 401 ├── SkirrePermissionError — 403 ├── SkirreNotFoundError — 404 └── SkirreRateLimitError — 429 SkirreTaskFailedError — thrown by waitForTask() when task status is "failed" SkirreTaskTimeoutError — thrown by waitForTask() when polling times out ``` ### SDK Error Properties ```typescript try { await index.search('test'); } catch (e) { if (e instanceof SkirreError) { e.code; // "not_found", "unauthorized", etc. e.status; // HTTP status code (0 for connection errors) e.message; // human-readable message e.retryAfter; // seconds (on 429) e.isRetryable; // true for 429 and 5xx e.isNotFound; // true for 404 } if (e instanceof SkirreTaskFailedError) { e.taskUid; // task UID e.taskError; // { code, message } } } ``` --- ## 23. Rate Limits & Retries ### SDK Auto-Retry The SDK automatically retries on: - HTTP 429 (rate limited) — respects `Retry-After` header - HTTP 5xx (server errors) - Network errors (connection failed, timeout) Retry behavior: - Max retries: `maxNetworkRetries` (default: 2) - Backoff: exponential with jitter (0.5s base, 5s cap) - `Retry-After` header respected (capped at 60s) ### Manual Retry Control ```typescript const skirre = new Skirre({ apiKey: '...', baseUrl: '...', maxNetworkRetries: 3, // increase retries timeout: 60_000, // increase timeout }); ``` Per-request timeout override: ```typescript // Via raw HTTP (if using the API directly) // The SDK doesn't expose per-request timeout yet, but the client.request() method accepts it internally ``` --- ## 24. Client-Side Analytics The SDK includes a browser-only `Analytics` class for automatic session tracking and page view collection. ### Automatic Setup ```typescript import { Skirre } from '@skirre/sdk'; const skirre = new Skirre({ apiKey: 'sk_search_live_...', baseUrl: 'https://search.example.com', }); // Start auto-tracking page views (call once in your app's entry point) skirre.analytics.start(); ``` ### What It Does 1. **Session ID**: Generates and stores a session ID in `sessionStorage` (`skirre_session_id`). Format: `sess_` + 16 alphanumeric chars. Dies when the tab closes — no cookies, no GDPR consent needed. 2. **Auto page views**: Fires a `page_view` event on: - Initial page load - Browser back/forward (`popstate`) - SPA navigation (`pushState`, `replaceState` — monkey-patched) 3. **Query attribution**: After each search, stores the `query_id` in `sessionStorage` (`skirre_last_query_id`). Automatically attached to subsequent events. ### Manual Usage ```typescript // Get or create session ID const sessionId = skirre.analytics.getSessionId(); // undefined in SSR // Get last query ID (for event attribution) const queryId = skirre.analytics.getLastQueryId(); // Stop auto-tracking (restores original History methods) skirre.analytics.stop(); ``` ### SSR Safety All browser APIs are guarded with `typeof window === 'undefined'` checks. The analytics class is a no-op in Node.js/SSR environments. --- ## 25. Migration Mapping Cheatsheets ### From Algolia | Algolia Concept | Skirre Equivalent | |----------------|-------------------| | Application ID + API Key | `baseUrl` + `apiKey` | | Index | `skirre.index('uid')` | | `searchableAttributes` | `searchable_attributes` in `CreateIndexParams` | | `attributesForFaceting` | `filterable_attributes` in `CreateIndexParams` | | `ranking` / `customRanking` | `attribute_weights` + `scoring` in settings | | `saveObjects()` | `index.addDocuments()` | | `partialUpdateObjects()` | `index.updateDocuments()` | | `search()` | `index.search()` | | `filters` (string) | `filter` (same string syntax concept — but different grammar, see §9) | | `facets` | `facets` param in search | | `facetFilters` (array) | Convert to filter string | | `numericFilters` | Convert to filter string (e.g. `price > 100`) | | `hitsPerPage` / `page` | `limit` / `offset` (offset-based, not page-based) | | `attributesToRetrieve` | `attributes_to_retrieve` | | `attributesToHighlight` | Automatic — Skirre highlights all searchable fields | | `synonyms` | `synonyms` in settings | | `typoTolerance` | `typo_tolerance` in settings | | `replicas` | Create separate indices + aliases | | `rules` | Not yet available (roadmap) | | Algolia Analytics | Skirre Analytics (per-index + account-level) | | Algolia Insights (events) | `skirre.sendEvents()` | | Secured API Keys | Tenant tokens (`skirre.createToken()`) | | `browseObjects()` | `index.getDocuments()` with pagination | **Key differences:** - Skirre writes are async (return `TaskInfo`). Use `*AndWait()` methods for synchronous behavior. - Filter syntax differs. Algolia uses `facetFilters: [["category:Electronics"]]` arrays. Skirre uses a string: `category = "Electronics"`. - Pagination is offset-based, not page-based. Convert: `offset = page * hitsPerPage`. ### From Meilisearch | Meilisearch Concept | Skirre Equivalent | |--------------------|-------------------| | Host + API Key | `baseUrl` + `apiKey` | | Index UID | Same concept — `skirre.index('uid')` | | `addDocuments()` | `index.addDocuments()` (same API shape) | | `updateDocuments()` | `index.updateDocuments()` (same API shape) | | `search()` | `index.search()` | | `filter` (string) | `filter` (very similar string syntax) | | `sort` | `sort` (same format: `['field:asc']`) | | `facets` | `facets` (same) | | `attributesToRetrieve` | `attributes_to_retrieve` (same) | | Task system | Almost identical — `task_uid`, polling, statuses | | `waitForTask()` | `skirre.waitForTask()` (same) | | Searchable attributes | `searchable_attributes` (with weights) | | Filterable attributes | `filterable_attributes` (with field types) | | Sortable attributes | `sortable_attributes` (same) | | Displayed attributes | `stored_attributes` in field config | | Synonyms | `synonyms` in settings (same format) | | Typo tolerance | `typo_tolerance` (same concept, similar config) | | `_matchesPosition` | Not available — use `highlights` instead | **Key differences:** - Skirre field config is set at index creation time (or via settings update), not as separate API calls per setting. - Skirre has searchable field weights (Meilisearch uses ordered list priority). - Filter syntax is very similar but not identical — test edge cases. - Skirre adds semantic search, behavioral events, scoring, and enrichment. ### From Typesense | Typesense Concept | Skirre Equivalent | |------------------|-------------------| | API Key + Host | `apiKey` + `baseUrl` | | Collection | Index (`skirre.index('uid')`) | | Collection schema (fields) | `CreateIndexParams` with `searchable_attributes`, `filterable_attributes` | | `documents.create()` | `index.addDocuments()` | | `documents.search()` | `index.search()` | | `filter_by` | `filter` (similar string syntax) | | `sort_by` | `sort` (format: `['field:asc']`) | | `facet_by` | `facets` | | `query_by` | Defined at index creation as `searchable_attributes` | | `query_by_weights` | `weight` on each `SearchableField` | | Scoped API Keys | Tenant tokens | | Synonyms | `synonyms` in settings | | Overrides (curations) | Not yet available (roadmap) | | Analytics | Skirre Analytics | **Key differences:** - Typesense requires a schema with explicit field types. Skirre configures which fields to index but documents are schemaless JSON. - Typesense `filter_by` syntax (`field:value`, `field:>100`) differs from Skirre (`field = "value"`, `field > 100`). - All Skirre writes are async (task-based). ### From Elasticsearch / OpenSearch | ES/OpenSearch Concept | Skirre Equivalent | |----------------------|-------------------| | Cluster + Credentials | `baseUrl` + `apiKey` | | Index (with mapping) | `skirre.createIndex()` with field config | | `_doc` / Bulk API | `index.addDocuments()` (JSON array, not NDJSON) | | `_search` / Query DSL | `index.search()` with string filter syntax | | `bool` query | `AND` / `OR` / `NOT` in filter string | | `term` / `match` query | Implicit in search query + filter | | `aggs` (aggregations) | `facets` (count-based only — no sum/avg/etc.) | | Aliases | `skirre.setAliases()` (same concept) | | Reindex API | `index.reindex()` | | Index Lifecycle | Manual — create new index, reindex, swap alias | | `_source` filtering | `attributes_to_retrieve` | | Synonyms | `synonyms` in settings | **Key differences:** - No Query DSL. Skirre uses a simple string filter language, not nested JSON queries. - Facets are count-based only (no aggregation pipeline). - Documents must have a flat or shallow structure — no nested objects as indexed fields. - All writes are async (task-based). ### From Shopify / WooCommerce (E-Commerce Platforms) These aren't search engines, but you may need to migrate product catalog data from them into Skirre. **General approach:** 1. Export products from the platform (API or CSV) 2. Transform each product into a Skirre document 3. Create an index with appropriate field config 4. Batch-upload documents 5. Configure synonyms, settings, and analytics **Suggested document shape for e-commerce:** ```typescript // Create index await skirre.createIndex({ uid: 'products', primary_key: 'id', searchable_attributes: [ { name: 'title', weight: 10 }, { name: 'description', weight: 5 }, { name: 'brand', weight: 3 }, { name: 'tags', weight: 2 }, { name: 'product_type', weight: 2 }, { name: 'sku', weight: 1 }, ], filterable_attributes: [ { name: 'price', field_type: 'number' }, { name: 'compare_at_price', field_type: 'number' }, { name: 'category', field_type: 'string' }, { name: 'brand', field_type: 'string' }, { name: 'product_type', field_type: 'string' }, { name: 'vendor', field_type: 'string' }, { name: 'in_stock', field_type: 'boolean' }, { name: 'tags', field_type: 'string' }, { name: 'created_at', field_type: 'string' }, ], sortable_attributes: ['price', 'created_at', 'title'], }); // Transform Shopify product → Skirre document function transformShopifyProduct(product: ShopifyProduct) { return { id: product.id.toString(), title: product.title, description: product.body_html?.replace(/<[^>]*>/g, '') ?? '', handle: product.handle, brand: product.vendor, vendor: product.vendor, product_type: product.product_type, tags: product.tags?.split(', ') ?? [], price: Math.min(...product.variants.map(v => parseFloat(v.price))), compare_at_price: product.variants[0]?.compare_at_price ? parseFloat(product.variants[0].compare_at_price) : null, in_stock: product.variants.some(v => v.inventory_quantity > 0), image_url: product.image?.src ?? null, images: product.images?.map(i => i.src) ?? [], sku: product.variants[0]?.sku ?? null, created_at: product.created_at, updated_at: product.updated_at, // Variant data flattened for filtering variant_count: product.variants.length, options: product.options?.map(o => o.name) ?? [], }; } // Batch upload (chunk into groups of 500–1000 for large catalogs) const BATCH_SIZE = 500; for (let i = 0; i < documents.length; i += BATCH_SIZE) { const batch = documents.slice(i, i + BATCH_SIZE); await index.addDocumentsAndWait(batch); } ``` **WooCommerce transformation is similar** — map `name` → `title`, `regular_price` → `price`, `categories[].name` → `category`, etc. --- ## Appendix A: Complete REST API Reference ### Health | Method | Path | Auth | Description | |--------|------|------|-------------| | `GET` | `/health` | None | Health check | ### Indices | Method | Path | Auth | Description | |--------|------|------|-------------| | `POST` | `/v1/indices` | Admin | Create index | | `GET` | `/v1/indices` | Admin | List indices | | `GET` | `/v1/indices/{uid}` | Admin | Get index info | | `DELETE` | `/v1/indices/{uid}` | Admin | Delete index (async) | ### Documents | Method | Path | Auth | Description | |--------|------|------|-------------| | `POST` | `/v1/indices/{uid}/documents` | Admin | Add/replace documents (async) | | `PATCH` | `/v1/indices/{uid}/documents` | Admin | Partial update documents (async) | | `GET` | `/v1/indices/{uid}/documents` | Admin | List documents | | `GET` | `/v1/indices/{uid}/documents/{id}` | Admin | Get single document | | `DELETE` | `/v1/indices/{uid}/documents/{id}` | Admin | Delete single document (async) | | `POST` | `/v1/indices/{uid}/documents/delete-batch` | Admin | Delete by IDs (async) | | `POST` | `/v1/indices/{uid}/documents/delete-by-filter` | Admin | Delete by filter (async) | ### Search | Method | Path | Auth | Description | |--------|------|------|-------------| | `POST` | `/v1/indices/{uid}/search` | Search | Full-text search | ### Similar | Method | Path | Auth | Description | |--------|------|------|-------------| | `POST` | `/v1/indices/{uid}/similar` | Search | Find similar documents | ### Settings | Method | Path | Auth | Description | |--------|------|------|-------------| | `GET` | `/v1/indices/{uid}/settings` | Admin | Get settings | | `PUT` | `/v1/indices/{uid}/settings` | Admin | Update settings (async) | ### Suggestions | Method | Path | Auth | Description | |--------|------|------|-------------| | `GET` | `/v1/indices/{uid}/suggestions` | Search | Autocomplete suggestions | ### Aliases | Method | Path | Auth | Description | |--------|------|------|-------------| | `PUT` | `/v1/aliases` | Admin | Atomic batch set | | `GET` | `/v1/aliases` | Admin | List aliases | | `DELETE` | `/v1/aliases/{name}` | Admin | Delete alias | ### Reindex & Reconcile | Method | Path | Auth | Description | |--------|------|------|-------------| | `POST` | `/v1/indices/{uid}/reindex` | Admin | Reindex from source (async) | | `POST` | `/v1/indices/{uid}/reconcile` | Admin | Fix store/index drift (async) | ### Tasks | Method | Path | Auth | Description | |--------|------|------|-------------| | `GET` | `/v1/tasks` | Admin | List tasks | | `GET` | `/v1/tasks/{uid}` | Admin | Get task | | `POST` | `/v1/tasks/cancel` | Admin | Cancel enqueued tasks | | `POST` | `/v1/tasks/delete` | Admin | Delete terminal tasks | ### Events | Method | Path | Auth | Description | |--------|------|------|-------------| | `POST` | `/v1/events` | Search | Send behavioral events (max 1000) | ### Analytics — Per-Index | Method | Path | Auth | Description | |--------|------|------|-------------| | `GET` | `/v1/indices/{uid}/analytics/top-queries` | Admin | Popular queries | | `GET` | `/v1/indices/{uid}/analytics/no-result-queries` | Admin | Zero-result queries | | `GET` | `/v1/indices/{uid}/analytics/events` | Admin | Event analytics | | `DELETE` | `/v1/indices/{uid}/analytics` | Admin | Clear all analytics data | | `GET` | `/v1/indices/{uid}/analytics/zero-result-suggestions` | Admin | Zero-result fix suggestions | | `POST` | `/v1/indices/{uid}/analytics/zero-result-suggestions/{id}/apply` | Admin | Apply suggestion | | `POST` | `/v1/indices/{uid}/analytics/zero-result-suggestions/{id}/dismiss` | Admin | Dismiss suggestion | | `POST` | `/v1/indices/{uid}/analytics/zero-result-suggestions/batch` | Admin | Batch resolve | | `GET` | `/v1/indices/{uid}/analytics/auto-synonym-suggestions` | Admin | Auto-synonym suggestions | | `POST` | `/v1/indices/{uid}/analytics/auto-synonym-suggestions/{id}/apply` | Admin | Apply synonym | | `POST` | `/v1/indices/{uid}/analytics/auto-synonym-suggestions/{id}/dismiss` | Admin | Dismiss synonym | | `POST` | `/v1/indices/{uid}/analytics/auto-synonym-suggestions/batch` | Admin | Batch resolve | ### Analytics — Account-Level | Method | Path | Auth | Description | |--------|------|------|-------------| | `GET` | `/v1/analytics/timeseries` | Admin | Search volume time series | | `GET` | `/v1/analytics/site` | Admin | Site-wide page view analytics | | `GET` | `/v1/analytics/search-funnel` | Admin | Search → purchase funnel | | `GET` | `/v1/analytics/search-origins` | Admin | Pages where search originates | ### Scoring | Method | Path | Auth | Description | |--------|------|------|-------------| | `GET` | `/v1/indices/{uid}/scoring` | Admin | Scoring config + stats | | `GET` | `/v1/indices/{uid}/scoring/top` | Admin | Top scored documents | | `GET` | `/v1/indices/{uid}/scoring/{document_id}` | Admin | Single document score | | `POST` | `/v1/indices/{uid}/scoring/recompute` | Admin | Trigger recomputation | ### Enrichment | Method | Path | Auth | Description | |--------|------|------|-------------| | `POST` | `/v1/indices/{uid}/enrichment/run` | Admin | Start enrichment job | | `GET` | `/v1/indices/{uid}/enrichment/jobs` | Admin | List jobs | | `GET` | `/v1/indices/{uid}/enrichment/jobs/{job_id}` | Admin | Get job status | | `GET` | `/v1/indices/{uid}/enrichment/suggestions` | Admin | List suggestions | | `POST` | `/v1/indices/{uid}/enrichment/suggestions/{id}/apply` | Admin | Apply suggestion | | `POST` | `/v1/indices/{uid}/enrichment/suggestions/{id}/dismiss` | Admin | Dismiss suggestion | | `POST` | `/v1/indices/{uid}/enrichment/suggestions/batch` | Admin | Batch resolve (max 100) | ### Keys | Method | Path | Auth | Description | |--------|------|------|-------------| | `POST` | `/v1/keys` | Admin | Create API key | | `GET` | `/v1/keys` | Admin | List keys | | `DELETE` | `/v1/keys/{id}` | Admin | Revoke key | ### Tenant Tokens | Method | Path | Auth | Description | |--------|------|------|-------------| | `POST` | `/v1/tokens` | Admin | Create scoped tenant token | --- ## Appendix B: Migration Checklist When migrating from any search platform to Skirre, follow this sequence: 1. **Create API key** — get an admin key from the Skirre dashboard or create one via API 2. **Design index schema** — map source fields to `searchable_attributes`, `filterable_attributes`, `sortable_attributes` 3. **Create the index** — `skirre.createIndex({ uid, primary_key, ...field_config })` 4. **Configure settings** — synonyms, typo tolerance, semantic search, language 5. **Transform documents** — map source document format to Skirre's flat JSON structure 6. **Batch upload** — chunk documents into batches of 500–1000, use `addDocumentsAndWait()` 7. **Verify** — search a few queries, check facets work, confirm document count matches 8. **Integrate search UI** — swap API calls from old provider to Skirre SDK 9. **Integrate events** — add click/purchase/page_view event tracking 10. **Set up aliases** — point an alias to the index for zero-downtime future reindexing 11. **Configure analytics** — enable scoring if using behavioral signals 12. **Test** — end-to-end search, filter, sort, facet, event tracking, analytics