Skip to main content

PHP Client

The hlquery PHP client provides a clean, object-oriented API for interacting with hlquery servers from PHP applications.

Features

  • No Dependencies: Uses PHP's built-in curl and json extensions
  • PSR-4 Autoloading: Modern autoloading support
  • 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 PHP client has no external dependencies. Simply include the autoloader:

require_once 'api/php/lib/autoload.php';

Or use Composer (if configured):

composer require hlquery/php-client

PDF Parsing Support

The PHP client does not currently support local PDF parsing helpers.

If you need to index PDF content, extract the text outside the PHP client first and then submit the parsed result as a normal hlquery document. PDF helper methods are currently available only in the Node.js and Python clients.

Quick Start

Basic Usage

require_once 'lib/autoload.php';

use Hlquery\Client;

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

// Health check
$health = $client->health();
echo "Status: " . $health->getStatusCode() . "\n";

// List collections
$collections = $client->listCollections(0, 10);
if ($collections->isSuccess()) {
$body = $collections->getBody();
echo "Found " . count($body['collections'] ?? []) . " collections\n";
}

With Authentication

// Method 1: Set token in constructor
$client = new Client('http://localhost:9200', [
'token' => 'your_token_here',
'auth_method' => 'bearer' // or 'api-key'
]);

// Method 2: Set token dynamically
$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

$client = new Client($baseUrl, $options = []);

Parameters:

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

Health & Status

health()

Check server health status.

$health = $client->health();
if ($health->isSuccess()) {
$body = $health->getBody();
echo "Status: " . $body['status'] . "\n";
}

stats()

Get server statistics.

$stats = $client->stats();
$body = $stats->getBody();
echo "Collections: " . $body['collections']['total'] . "\n";

info()

Get server information.

$info = $client->info();

Collections API

Using Collections API Object

$collections = $client->collections();

// List collections
$result = $collections->list(0, 10);

// Get collection
$result = $collections->get('my_collection');

// Create collection
$schema = [
'fields' => [
['name' => 'title', 'type' => 'string'],
['name' => 'price', 'type' => 'float']
]
];
$result = $collections->create('new_collection', $schema);

// Delete collection
$result = $collections->delete('collection_name');

// Update collection
$result = $collections->update('collection_name', [
'fields' => [['name' => 'new_field', 'type' => 'string']]
]);

Direct Methods

// List collections
$collections = $client->listCollections($offset, $limit);

// Get collection
$collection = $client->getCollection('collection_name');

// Create collection
$result = $client->createCollection('collection_name', $schema);

// Delete collection
$result = $client->deleteCollection('collection_name');

Documents API

Using Documents API Object

$documents = $client->documents();

// List documents
$result = $documents->list('collection_name', 0, 10);

// Get document
$result = $documents->get('collection_name', 'document_id');

// Add document
$doc = [
'id' => 'doc1',
'title' => 'Example',
'price' => 99.99
];
$result = $documents->add('collection_name', $doc);

// Update document
$result = $documents->update('collection_name', 'doc_id', $doc);

// Delete document
$result = $documents->delete('collection_name', 'doc_id');

// Import documents (bulk)
$docs = [$doc1, $doc2, $doc3];
$result = $documents->import('collection_name', $docs);

Direct Methods

// List documents
$docs = $client->listDocuments('collection_name', $offset, $limit);

// Get document
$doc = $client->getDocument('collection_name', 'doc_id');

// Add document
$result = $client->addDocument('collection_name', $doc);

// Update document
$result = $client->updateDocument('collection_name', 'doc_id', $doc);

// Delete document
$result = $client->deleteDocument('collection_name', 'doc_id');

// Import documents
$result = $client->importDocuments('collection_name', $docs);

Search API

Using Search API Object

$search = $client->search();

// Perform search
$result = $search->perform('collection_name', [
'q' => 'laptop',
'query_by' => 'title,description',
'filter_by' => 'price:>1000',
'sort_by' => 'price:asc',
'limit' => 10
]);

// Multi-search
$searches = [
['collection' => 'products', 'q' => 'laptop'],
['collection' => 'articles', 'q' => 'laptop']
];
$result = $search->multi($searches);

// Vector search
$result = $search->vector('collection_name', [
'vector' => [0.1, 0.2, 0.3],
'limit' => 10
]);

Direct Methods

// Search
$results = $client->search('collection_name', [
'q' => 'laptop',
'query_by' => 'title'
]);

// Multi-search
$results = $client->multiSearch($searches);

// Vector search
$results = $client->vectorSearch('collection_name', [
'vector' => [0.1, 0.2, 0.3]
]);

SQL API

Using SQL API Object

$sql = $client->sql();

// Collection-bound SELECT
$result = $sql->query(
'products',
'SELECT id, title, price FROM products ORDER BY price DESC LIMIT 5;'
);

// Top-level SQL query
$result = $sql->raw('SHOW COLLECTIONS;');

// Top-level SQL statement
$result = $sql->execute(
"INSERT INTO products (id, title, price) VALUES ('sku_9', 'Camp Stove', 89);"
);

The nested SQL object keeps the API shape consistent with other service objects like $client->collections() and $client->documents().

Response Objects

All API methods return a Response object with helper methods:

$response = $client->health();

// Get HTTP status code
$statusCode = $response->getStatusCode();

// Get response body
$body = $response->getBody();

// Check if successful
if ($response->isSuccess()) {
// Handle success
}

// Check if error
if ($response->isError()) {
$error = $response->getError();
echo "Error: $error\n";
}

// Convert to array format (for backward compatibility)
$array = $response->toArray();

Error Handling

The client throws custom exceptions:

use Hlquery\HlqueryException;
use Hlquery\AuthenticationException;
use Hlquery\RequestException;

try {
$result = $client->createCollection('collection', $schema);
} catch (AuthenticationException $e) {
echo "Authentication failed: " . $e->getMessage() . "\n";
} catch (RequestException $e) {
echo "Request failed: " . $e->getMessage() . "\n";
} catch (HlqueryException $e) {
echo "Error: " . $e->getMessage() . "\n";
}

Examples

See the examples/ directory for complete examples:

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

Testing

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

Quick Start

cd api/php/tests
php test_get_document.php
php test_search.php
php test_filter_search.php

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.

Next Steps