Skip to main content

Node.js Client

The hlquery Node.js client provides a modern, async/await-based API for interacting with hlquery servers from Node.js and TypeScript applications.

Features

  • No External Dependencies: Uses Node.js built-in http and https modules
  • Async/Await Support: Modern async/await syntax throughout
  • Type-safe Responses: Response objects with helper methods
  • Consistent API Design: Familiar structure for developers
  • Authentication Support: Bearer token and X-API-Key authentication
  • Comprehensive Validation: Input validation for all operations

Installation

The Node.js client has no external dependencies. Simply copy the client files to your project:

# Copy the client library
cp -r api/node/lib ./node_modules/hlquery-client

# Or use directly
const Client = require('./api/node/lib/Client');

Optional PDF Support

If you want to index local PDF files directly through the Node.js client, install the optional parser:

npm install pdf-parse

The client exposes documents().addPDF(collection, filePath, options) to parse the PDF locally, normalize the extracted content, and submit it as a regular hlquery document.

Quick Start

Basic Usage

const Client = require('./lib/Client');

// Initialize client
const client = new Client('http://localhost:9200');

// Health check
const health = await client.health();
console.log('Status:', health.getStatusCode());

// List collections
const collections = await client.listCollections(0, 10);
if (collections.isSuccess()) {
const body = collections.getBody();
console.log(`Found ${body.collections?.length || 0} collections`);
}

With Authentication

// Method 1: Set token in constructor
const client = new Client('http://localhost:9200', {
token: 'your_token_here',
auth_method: 'bearer' // or 'api-key'
});

// Method 2: Set token dynamically
const client = new Client('http://localhost:9200');
client.setAuthToken('your_token_here', 'bearer');

// Method 3: Use X-API-Key
client.setAuthToken('your_token_here', 'api-key');

API Reference

Client Initialization

const client = new Client(baseUrl, options);

Parameters:

  • baseUrl (string, required): Base URL of hlquery server (e.g., 'http://localhost:9200')
  • options (object, optional): Client options
    • token (string): Authentication token
    • auth_method (string): Authentication method ('bearer' or 'api-key')
    • timeout (number): Request timeout in milliseconds

Health & Status

health()

Check server health status.

const health = await client.health();
if (health.isSuccess()) {
const body = health.getBody();
console.log('Status:', body.status);
}

stats()

Get server statistics.

const stats = await client.stats();
const body = stats.getBody();
console.log('Collections:', body.collections?.total);

info()

Get server information.

const info = await client.info();

Collections API

Using Collections API Object

const collections = client.collections();

// List collections
const result = await collections.list(0, 10);

// Get collection
const result = await collections.get('my_collection');

// Create collection
const schema = {
fields: [
{name: 'title', type: 'string'},
{name: 'price', type: 'float'}
]
};
const result = await collections.create('new_collection', schema);

// Delete collection
const result = await collections.delete('collection_name');

// Update collection
const result = await collections.update('collection_name', {
fields: [{name: 'new_field', type: 'string'}]
});

Direct Methods

// List collections
const collections = await client.listCollections(offset, limit);

// Get collection
const collection = await client.getCollection('collection_name');

// Create collection
const result = await client.createCollection('collection_name', schema);

// Delete collection
const result = await client.deleteCollection('collection_name');

Documents API

Using Documents API Object

const documents = client.documents();

// List documents
const result = await documents.list('collection_name', 0, 10);

// Get document
const result = await documents.get('collection_name', 'document_id');

// Add document
const doc = {
id: 'doc1',
title: 'Example',
price: 99.99
};
const result = await documents.add('collection_name', doc);

// Update document
const result = await documents.update('collection_name', 'doc_id', doc);

// Delete document
const result = await documents.delete('collection_name', 'doc_id');

// Import documents (bulk)
const docs = [doc1, doc2, doc3];
const result = await documents.import('collection_name', docs);

// Parse and add a local PDF file
const pdfResult = await documents.addPDF('collection_name', './files/report.pdf', {
document: {
source_type: 'pdf'
}
});

Direct Methods

// List documents
const docs = await client.listDocuments('collection_name', offset, limit);

// Get document
const doc = await client.getDocument('collection_name', 'doc_id');

// Add document
const result = await client.addDocument('collection_name', doc);

// Update document
const result = await client.updateDocument('collection_name', 'doc_id', doc);

// Delete document
const result = await client.deleteDocument('collection_name', 'doc_id');

// Import documents
const result = await client.importDocuments('collection_name', docs);

Search API

Using Search API Object

const search = client.searchApi();

// Perform search
const result = await search.search('collection_name', {
q: 'laptop',
query_by: 'title,description',
filter_by: 'price:>1000',
sort_by: 'price:asc',
limit: 10
});

// Multi-search
const searches = [
{collection: 'products', q: 'laptop'},
{collection: 'articles', q: 'laptop'}
];
const result = await search.multiSearch(searches); // POST by default
const getResult = await search.multiSearch(searches, 'GET');

// Vector search
const result = await search.vectorSearch('collection_name', {
vector: [0.1, 0.2, 0.3, ...],
limit: 10
});

Direct Methods

// Search
const results = await client.search('collection_name', {
q: 'laptop',
query_by: 'title'
});

// Multi-search
const results = await client.multiSearch(searches);

// Vector search
const results = await client.vectorSearch('collection_name', {
vector: [0.1, 0.2, 0.3, ...]
});

Response Objects

All API methods return a Response object with helper methods:

const response = await client.health();

// Get HTTP status code
const statusCode = response.getStatusCode();

// Get response body
const body = response.getBody();

// Check if successful
if (response.isSuccess()) {
// Handle success
}

// Check if error
if (response.isError()) {
const error = response.getError();
console.error('Error:', error);
}

// Convert to array format (for backward compatibility)
const array = response.toArray();

Error Handling

The client throws custom exceptions:

const { HlqueryException, AuthenticationException, RequestException } = require('./lib/Exceptions');

try {
const result = await client.createCollection('collection', schema);
} catch (error) {
if (error instanceof AuthenticationException) {
console.error('Authentication failed');
} else if (error instanceof RequestException) {
console.error('Request failed:', error.message);
} else {
console.error('Error:', error.message);
}
}

Testing

The Node.js API includes a comprehensive test suite with 31 test scripts covering all API functionality.

Quick Start

cd api/node/tests
node test_get_document.js
node test_search.js
node test_filter_search.js

Test Documentation

All tests are self-contained, create their own test data, and include detailed developer comments explaining what each test does and how to run it.

Examples

See the examples/ directory for complete examples:

  • basic_usage.js - Basic usage examples
  • collections.js - Collection management
  • documents.js - Document CRUD operations
  • search.js - Search operations
  • vector.js - Vector search examples

Next Steps