Skip to content

@inferedge/moss v1.0.0-beta.1


@inferedge/moss / MossClient

Class: MossClient

MossClient - Semantic search client for vector similarity operations.

Example

typescript
const client = new MossClient('your-api-key');
await client.createIndex('docs', 'moss-minilm');
await client.addItems('docs', [
  { id: '1', text: 'Machine learning fundamentals' },
  { id: '2', text: 'Deep learning neural networks' }
]);
const results = await client.query('docs', 'AI and neural networks');

Constructors

Constructor

new MossClient(apiKey): MossClient

Creates a new MossClient instance.

Parameters

apiKey

string

Your Moss API authentication key.

Returns

MossClient

Methods

addItem()

addItem(indexId, item): Promise<void>

Adds a single item to an index and generates its embedding.

Parameters

indexId

string

Target index identifier.

item

Item

Item to add with ID and text content.

Returns

Promise<void>

Throws

Error if index not found or item ID already exists.

Example

typescript
await client.addItem('docs', { id: '1', text: 'Machine learning intro' });

addItems()

addItems(indexId, items): Promise<void>

Adds multiple items to an index in a batch operation.

Parameters

indexId

string

Target index identifier.

items

Item[]

Array of items to add.

Returns

Promise<void>

Throws

Error if index not found or any item ID already exists.

Example

typescript
await client.addItems('docs', [
  { id: '1', text: 'Machine learning fundamentals' },
  { id: '2', text: 'Deep learning neural networks' }
]);

clearIndex()

clearIndex(indexId): void

Removes all items from the specified index while keeping the index structure intact.

This operation permanently deletes all items and their associated embedding vectors, but preserves the index configuration (model, dimensions, etc.) for future use.

Parameters

indexId

string

The identifier of the target index.

Returns

void

Throws

If the specified index does not exist.

Example

typescript
client.clearIndex('documents');
console.log('All items removed from index');

// Index still exists and can be used
await client.addItem('documents', { id: '1', text: 'New content' });

createIndex()

createIndex(id, modelId, dimension?, metric?, textFieldId?): Promise<boolean>

Creates a new semantic search index.

Parameters

id

string

Unique identifier for this index.

modelId

MossModel

Embedding model: 'moss-minilm' (faster) or 'moss-mediumlm' (more accurate).

dimension?

number

Optional. Embedding vector dimension (uses model default if not specified).

metric?

string

Optional. Distance metric for similarity calculation (default: 'cosine').

textFieldId?

string

Optional. Field identifier for text content (default: 'text').

Returns

Promise<boolean>

Promise resolving to true when created successfully.

Throws

Error if index ID already exists.

Example

typescript
await client.createIndex('my-docs', 'moss-minilm');
await client.createIndex('research', 'moss-mediumlm', 768, 'cosine');

deleteIndex()

deleteIndex(id): boolean

Permanently deletes an index and all its data.

Parameters

id

string

Index identifier to delete.

Returns

boolean

true if deleted successfully, false if not found.

Example

typescript
const deleted = client.deleteIndex('old-index');

exportIndexAsBinary()

exportIndexAsBinary(indexId): ArrayBuffer

Exports an index as binary data for backup, transfer, or persistence purposes.

The exported data contains all index configuration, items, and pre-computed embeddings in a compact binary format that can be saved to disk or transferred between systems.

Parameters

indexId

string

The identifier of the index to export.

Returns

ArrayBuffer

An ArrayBuffer containing the serialized index data.

Throws

If the specified index does not exist or if serialization fails.

Example

typescript
// Export index to binary
const binaryData = client.exportIndexAsBinary('documents');

// Save to file (Node.js example)
import { writeFileSync } from 'fs';
writeFileSync('documents-backup.moss', Buffer.from(binaryData));

// Or convert to base64 for storage
const base64Data = Buffer.from(binaryData).toString('base64');

getItem()

getItem(indexId, itemId): undefined | Item

Retrieves a specific item from the specified index by its ID.

Parameters

indexId

string

The identifier of the target index.

itemId

The ID of the item to retrieve.

string | number

Returns

undefined | Item

The item object if found, or undefined if the item does not exist in the index.

Throws

If the specified index does not exist.

Example

typescript
const item = client.getItem('documents', 'doc-001');
if (item) {
  console.log('Found item:', item.text);
} else {
  console.log('Item not found');
}

getItemCount()

getItemCount(indexId): number

Returns the total number of items currently stored in the specified index.

Parameters

indexId

string

The identifier of the target index.

Returns

number

The number of items in the index (0 if empty).

Throws

If the specified index does not exist.

Example

typescript
const count = client.getItemCount('documents');
console.log(`The index contains ${count} items`);

getItems()

getItems(indexId): Item[]

Retrieves all items from the specified index.

Parameters

indexId

string

The identifier of the target index.

Returns

Item[]

An array of all items in the index. Returns an empty array if the index contains no items.

Throws

If the specified index does not exist.

Example

typescript
const allItems = client.getItems('documents');
console.log(`Index contains ${allItems.length} items`);
allItems.forEach(item => console.log(`${item.id}: ${item.text}`));

hasIndex()

hasIndex(id): boolean

Checks if an index exists.

Parameters

id

string

Index identifier to check.

Returns

boolean

true if index exists, false otherwise.


listIndexes()

listIndexes(): string[]

Lists all index identifiers.

Returns

string[]

Array of index IDs.


loadIndexFromBinary()

loadIndexFromBinary(binaryData): Promise<string>

Loads an index from binary data previously created with exportIndexAsBinary.

This method recreates a complete index including all items, embeddings, and configuration from the binary data. The loaded index will be immediately available for search operations.

Parameters

binaryData

ArrayBuffer

The binary data (ArrayBuffer) containing the serialized index, typically created by a previous call to exportIndexAsBinary.

Returns

Promise<string>

Promise that resolves to the ID of the successfully imported index. This ID can be used immediately for search and data operations.

Throws

If the binary data is invalid, corrupted, or if an index with the same ID already exists.

Example

typescript
// Load from file (Node.js example)
import { readFileSync } from 'fs';
const binaryData = readFileSync('documents-backup.moss').buffer;

// Import the index
const indexId = await client.loadIndexFromBinary(binaryData);
console.log(`Index '${indexId}' loaded successfully`);

// Index is immediately ready for use
const results = await client.query(indexId, 'search query');

// Load from base64 string
const base64Data = 'SGVsbG8gV29ybGQ='; // example
const buffer = Uint8Array.from(atob(base64Data), c => c.charCodeAt(0)).buffer;
const loadedIndexId = await client.loadIndexFromBinary(buffer);

query()

query(indexId, query, options?): Promise<SearchResult>

Performs a semantic similarity search against the specified index.

This method converts the query text into an embedding vector using the same model as the index, then finds the most semantically similar items based on vector similarity.

Parameters

indexId

string

The identifier of the target index to search.

query

string

The search query text. This will be converted to an embedding for comparison.

options?

QueryOptions

Optional search configuration parameters.

Returns

Promise<SearchResult>

Promise that resolves to a SearchResult object containing: - query: The original search query - matches: Array of matching items with similarity scores (0-1, higher is more similar) - metrics: Performance timing data (if requested)

Throws

If the specified index does not exist.

Example

typescript
// Basic search
const results = await client.query('documents', 'machine learning algorithms');
console.log(`Found ${results.matches.length} matches`);
results.matches.forEach(match => {
  console.log(`${match.id}: ${match.text} (score: ${match.score.toFixed(3)})`);
});

// Search with options
const detailedResults = await client.query('documents', 'neural networks', {
  topResultsCount: 10,
  measurePerformance: true
});
console.log('Search took:', detailedResults.metrics?.totalTime, 'ms');

removeItem()

removeItem(indexId, itemId): boolean

Removes an item from the specified index.

This permanently deletes the item and its associated embedding vector from the index. The operation cannot be undone.

Parameters

indexId

string

The identifier of the target index.

itemId

The ID of the item to remove.

string | number

Returns

boolean

true if the item was successfully removed, false if the item was not found.

Throws

If the specified index does not exist.

Example

typescript
const removed = client.removeItem('documents', 'doc-001');
if (removed) {
  console.log('Item removed successfully');
} else {
  console.log('Item not found');
}

updateItem()

updateItem(indexId, itemId, item): Promise<boolean>

Updates an existing item in the specified index with new content.

The updated text content will be re-processed through the embedding model to generate a new vector representation, replacing the previous one.

Parameters

indexId

string

The identifier of the target index.

itemId

The ID of the item to update.

string | number

item

Item

The updated item data containing new text content.

Returns

Promise<boolean>

Promise that resolves to true if the item was successfully updated, or false if the item was not found in the index.

Throws

If the specified index does not exist.

Example

typescript
const updated = await client.updateItem('documents', 'doc-001', {
  id: 'doc-001',
  text: 'Updated: Advanced machine learning algorithms and their practical applications'
});

if (updated) {
  console.log('Item updated successfully');
} else {
  console.log('Item not found');
}