VectorIndex class for managing vector indexes

This class represents a vector index in the Mosaia platform, which is used for semantic search and similarity matching.

Hierarchy (View Summary)

Constructors

Methods

  • Check if the entity is active

    This method checks the active status of the entity. Most entities in the system can be active or inactive, which affects their availability and usability in the platform.

    Returns boolean

    True if the entity is active, false otherwise

    const user = new User(userData);
    if (user.isActive()) {
    // Perform operations with active user
    } else {
    console.log('User is inactive');
    }
  • Convert model instance to interface data

    This method serializes the model instance to a plain object that matches the interface type. This is useful for:

    • Sending data to the API
    • Storing data in a database
    • Passing data between components
    • Debugging model state

    Returns VectorIndexInterface

    The model data as a plain object matching the interface type

    const user = new User({
    email: 'user@example.com',
    firstName: 'John'
    });

    const data = user.toJSON();
    console.log(data); // { email: '...', firstName: '...' }

    // Use with JSON.stringify
    const json = JSON.stringify(user);
  • Convert model instance to API payload

    This method creates a payload suitable for API requests by:

    • Converting the model to a plain object
    • Removing read-only fields (like 'id')
    • Ensuring proper data format for the API

    Returns Partial<VectorIndexInterface>

    A clean object suitable for API requests

    const user = new User({
    id: '123', // Will be removed from payload
    email: 'new@example.com',
    firstName: 'John'
    });

    const payload = user.toAPIPayload();
    // payload = { email: '...', firstName: '...' }
    // Note: 'id' is removed as it's read-only

    await apiClient.POST('/users', payload);
  • Update model data with new values

    This method updates the model's data and instance properties with new values. It performs a shallow merge of the updates with existing data, allowing for partial updates of the model's properties.

    Parameters

    Returns void

    const user = new User({
    email: 'old@example.com',
    firstName: 'John'
    });

    // Update multiple properties
    user.update({
    email: 'new@example.com',
    lastName: 'Doe'
    });

    // Save changes to API
    await user.save();

    This method only updates the local model instance. To persist changes to the API, call save after updating.

  • Save the model instance to the API

    This method persists the current state of the model to the API using a PUT request. It requires the model to have an ID (existing instance). For new instances, use the collection's create method instead.

    The method:

    1. Validates the model has an ID
    2. Sends current data to the API
    3. Updates local instance with API response

    Returns Promise<VectorIndexInterface>

    Promise resolving to the updated model data

    When model has no ID

    When API request fails

    const user = new User({
    id: '123',
    email: 'user@example.com'
    });

    // Update and save
    user.update({ firstName: 'John' });
    await user.save();

    Error handling:

    try {
    await user.save();
    } catch (error) {
    if (error.message.includes('ID is required')) {
    // Handle missing ID error
    } else {
    // Handle API errors
    }
    }
  • Delete the model instance from the API

    This method permanently deletes the model instance from the API and clears the local data. This operation cannot be undone.

    The method:

    1. Validates the model has an ID
    2. Sends DELETE request to the API
    3. Clears local instance data on success

    Parameters

    • Optionalparams: object

      Optional query parameters for deletion (e.g., { delete: true, deleteS3: true })

    Returns Promise<void>

    Promise that resolves when deletion is successful

    When model has no ID

    When API request fails

    Basic deletion:

    const user = await users.get({}, 'user-id');
    if (user) {
    await user.delete();
    // User is now deleted and instance is cleared
    }

    Error handling:

    try {
    await user.delete();
    console.log('User deleted successfully');
    } catch (error) {
    if (error.message.includes('ID is required')) {
    console.error('Cannot delete - no ID');
    } else {
    console.error('Deletion failed:', error.message);
    }
    }

    Delete with query parameters:

    // Hard delete
    await item.delete({ delete: true });

    // Delete with S3 cleanup
    await item.delete({ deleteS3: true, delete: true });
  • Reindexes all files associated with this VectorIndex

    This method triggers asynchronous reindexing of all files in the VectorIndex:

    • Deletes all existing Vector documents for this index
    • Queues a reindex job to storage-manager via SQS
    • Storage-manager finds all files (recursively if folder-based) and sends to document-parser
    • Returns immediately after queuing (async processing)

    The reindex operation will process:

    • If folder is set: All files recursively in that folder (folder takes precedence over drive)
    • If drive is set (and no folder): All files in that drive
    • Only ACTIVE FILE type DriveItems are processed

    Returns Promise<ReindexFilesResponse>

    Promise resolving to reindex result with status and deleted vectors count

    When VectorIndex instance has no ID

    When API request fails

    // Reindex all files in a folder-level index
    const vectorIndex = await vectorIndexes.getById('index-id');
    const result = await vectorIndex.reindexFiles();
    // Returns: { deletedVectors: 100, status: "queued", message: "Reindex job has been queued..." }
    // Reindex all files in a drive-level index
    const vectorIndex = await vectorIndexes.getById('index-id');
    const result = await vectorIndex.reindexFiles();
    console.log(`Deleted ${result.deletedVectors} vectors, status: ${result.status}`);
  • Performs RAG (Retrieval-Augmented Generation) search within this VectorIndex

    This method performs a complete RAG pipeline: generates embeddings for a query, searches the vector index for relevant documents, and reranks the results using a reranking model. It searches only within this VectorIndex.

    Parameters

    • query: string

      The search query to process

    • Optionaloptions: {
          limit?: number;
          params?: Record<string, any>;
          exclude?: string[];
          embeddingModelId?: string;
          rerankModelId?: string;
      } = {}

      Search options

      • Optionallimit?: number

        Maximum number of results to return

      • Optionalparams?: Record<string, any>

        Additional metadata filters for vector search

      • Optionalexclude?: string[]

        Array of document IDs or content to exclude from results

      • OptionalembeddingModelId?: string

        Custom embedding model ID to use (optional)

      • OptionalrerankModelId?: string

        Custom reranking model ID to use (optional)

    Returns Promise<RAGSearchResponse>

    Promise resolving to RAG search results with documents and paging

    When VectorIndex instance has no ID

    When API request fails

    // Basic RAG search
    const vectorIndex = await vectorIndexes.getById('index-id');
    const results = await vectorIndex.search('machine learning algorithms');
    // Returns: { documents: [{ document: "...", index: 0, relevance_score: 0.95 }, ...], paging: {...} }
    // RAG search with options
    const results = await vectorIndex.search('AI best practices', {
    limit: 20,
    params: { category: 'technical' },
    exclude: ['doc-id-1', 'doc-id-2'],
    embeddingModelId: 'custom-embedding-model',
    rerankModelId: 'custom-rerank-model'
    });

    results.documents.forEach((doc, idx) => {
    console.log(`Result ${idx}: ${doc.document.substring(0, 100)}... (score: ${doc.relevance_score})`);
    });