Skip to main content

PHP Client Examples

Comprehensive examples for the hlquery PHP client library.

Example Files

The PHP client includes several example files demonstrating different aspects of the API:

  • basic_usage.php - Basic client initialization and simple operations
  • collections.php - Collection management operations
  • documents.php - Document CRUD operations
  • search.php - Various search patterns and options
  • vector.php - Vector search capabilities with multiple collections

Running Examples

Main Example File

The main example file (example.php) provides a comprehensive demonstration of all API features:

# Run all examples (default)
php example.php

# Run specific command
php example.php cols # List collections
php example.php docs my_collection # List documents in collection
php example.php status # Show server health and status
php example.php demo # Quick demo: stats, ping, create collection, add doc, list
php example.php help # Show help message

Individual Example Files

# Basic usage
php examples/basic_usage.php

# Collections
php examples/collections.php

# Documents
php examples/documents.php

# Search
php examples/search.php

# Vector search
php examples/vector.php

Example Output

Running php examples/basic_usage.php against a local server can look like this:

Health Status: 200
Health Body: {
"auth_enabled": false,
"auth_required": false,
"demo_mode": false,
"engine": "epoll",
"health_degraded": false,
"loaded_modules": [
"test",
"banned",
"lang",
"analytics"
],
"readonly_mode": false,
"server": "hlquery",
"socket_engine": "epoll",
"status": "ok",
"version": "1.0"
}
Found 0 collections

That is the payload you get back from the PHP client when you call $response->getBody().

Basic Operations

Initialize Client

require_once 'lib/autoload.php';
use Hlquery\Client;

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

// With authentication
$client = new Client('http://localhost:9200', [
'token' => 'your_token_here'
]);

// Or set token dynamically
$client->setAuthToken('your_token_here', 'bearer');

Health Check

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

Typical $health->getBody() result:

[
'auth_enabled' => false,
'auth_required' => false,
'demo_mode' => false,
'engine' => 'epoll',
'health_degraded' => false,
'loaded_modules' => ['test', 'banned', 'lang', 'analytics'],
'readonly_mode' => false,
'server' => 'hlquery',
'socket_engine' => 'epoll',
'status' => 'ok',
'version' => '1.0',
]

Server Statistics

$stats = $client->stats();
if ($stats->isSuccess()) {
$body = $stats->getBody();
echo "Collections: " . ($body['collections']['total'] ?? 0) . "\n";
echo "Documents: " . ($body['documents']['total'] ?? 0) . "\n";
}

Typical response shape:

[
'collections' => [
'total' => 12,
],
'documents' => [
'total' => 100100,
],
'memory' => [
'used' => 12345678,
],
'uptime' => 3456,
]

The exact numbers depend on your running server state. The important part is the array shape returned by $stats->getBody().

Collection Management

List Collections

$collections = $client->collections()->list(0, 10);
if ($collections->isSuccess()) {
$body = $collections->getBody();
foreach ($body['collections'] as $col) {
$name = is_array($col) ? ($col['name'] ?? $col) : $col;
echo "Collection: $name\n";
}
}

Create Collection

$schema = [
'fields' => [
['name' => 'title', 'type' => 'string'],
['name' => 'content', 'type' => 'string'],
['name' => 'price', 'type' => 'float'],
['name' => 'embedding', 'type' => 'float[]']
]
];
$result = $client->collections()->create('products', $schema);
if ($result->isSuccess()) {
echo "Collection created\n";
}

Get Collection Details

$collection = $client->collections()->get('products');
if ($collection->isSuccess()) {
$body = $collection->getBody();
echo "Collection: " . $body['name'] . "\n";
echo "Fields: " . count($body['fields']) . "\n";
}

Get Collection Fields

$fields = $client->collections()->getFields('products');
if ($fields->isSuccess()) {
$body = $fields->getBody();
foreach ($body['fields'] as $field) {
echo "Field: {$field['name']} ({$field['type']})\n";
}
}

Delete Collection

$result = $client->collections()->delete('products');
if ($result->isSuccess()) {
echo "Collection deleted\n";
}

Document Operations

Add Document

$product = [
'id' => 'prod_001',
'title' => 'Laptop',
'content' => 'High-performance laptop',
'price' => 999.99
];
$result = $client->documents()->add('products', $product);
if ($result->isSuccess()) {
echo "Document added\n";
}

Get Document

$doc = $client->documents()->get('products', 'prod_001');
if ($doc->isSuccess()) {
$body = $doc->getBody();
echo "Title: " . $body['title'] . "\n";
echo "Price: " . $body['price'] . "\n";
}

Update Document

$updated = [
'title' => 'Updated Laptop',
'price' => 899.99
];
$result = $client->documents()->update('products', 'prod_001', $updated);
if ($result->isSuccess()) {
echo "Document updated\n";
}

List Documents

$documents = $client->documents()->list('products', [
'offset' => 0,
'limit' => 10
]);
if ($documents->isSuccess()) {
$body = $documents->getBody();
foreach ($body['documents'] as $doc) {
echo "ID: " . $doc['id'] . " - " . $doc['title'] . "\n";
}
}

Bulk Import

$products = [
['id' => 'prod_001', 'title' => 'Laptop', 'price' => 999.99],
['id' => 'prod_002', 'title' => 'Mouse', 'price' => 29.99],
['id' => 'prod_003', 'title' => 'Keyboard', 'price' => 79.99]
];
$result = $client->documents()->import('products', $products);
if ($result->isSuccess()) {
$body = $result->getBody();
echo "Imported: " . ($body['num_imported'] ?? count($products)) . " documents\n";
}

Delete Document

$result = $client->documents()->delete('products', 'prod_001');
if ($result->isSuccess()) {
echo "Document deleted\n";
}

Search Examples

$result = $client->search('products', [
'q' => 'laptop',
'query_by' => 'title,content',
'limit' => 10
]);
if ($result->isSuccess()) {
$body = $result->getBody();
foreach ($body['hits'] as $hit) {
$doc = $hit['document'] ?? $hit;
echo $doc['title'] . " (score: " . ($hit['text_match'] ?? 'N/A') . ")\n";
}
}

Search with Filters

$result = $client->search('products', [
'q' => 'laptop',
'query_by' => 'title',
'filter_by' => 'price:>500',
'sort_by' => 'price:asc',
'limit' => 20
]);

Search with Highlighting

$result = $client->search('products', [
'q' => 'laptop',
'query_by' => 'title,content',
'highlight' => true,
'highlight_fields' => ['title', 'content'],
'limit' => 10
]);
if ($result->isSuccess()) {
$body = $result->getBody();
foreach ($body['hits'] as $hit) {
if (isset($hit['highlights'])) {
echo "Highlighted title: " . $hit['highlights']['title'] . "\n";
}
}
}

Advanced Query Types

// Field-specific search
$result = $client->search('products', [
'q' => 'title:laptop',
'query_by' => 'title,content',
'limit' => 10
]);

// Range query
$result = $client->search('products', [
'q' => 'price:[100 TO 500]',
'query_by' => 'title,content',
'limit' => 10
]);

// Fuzzy search
$result = $client->search('products', [
'q' => 'laptop~2',
'query_by' => 'title,content',
'limit' => 10
]);

// Wildcard search
$result = $client->search('products', [
'q' => 'laptop*',
'query_by' => 'title,content',
'limit' => 10
]);
$vectorQuery = [0.1, 0.2, 0.3, 0.4, 0.5];
$result = $client->vectorSearch('products', [
'vector_query' => $vectorQuery,
'limit' => 10,
'threshold' => 0.5,
'normalize' => true
]);
if ($result->isSuccess()) {
$body = $result->getBody();
foreach ($body['hits'] as $hit) {
$doc = $hit['document'] ?? $hit;
$similarity = $hit['similarity_score'] ?? 'N/A';
echo $doc['title'] . " (similarity: $similarity)\n";
}
}
$result = $client->searchApi()->multiSearch([
['collection' => 'products', 'q' => 'laptop', 'query_by' => 'title'],
['collection' => 'articles', 'q' => 'laptop', 'query_by' => 'content']
]);

Error Handling

use Hlquery\HlqueryException;
use Hlquery\AuthenticationException;

try {
$result = $client->collections()->create('test', $schema);
if (!$result->isSuccess()) {
echo "Error: " . $result->getStatusCode() . "\n";
$error = $result->getBody();
echo "Message: " . ($error['message'] ?? 'Unknown error') . "\n";
}
} catch (AuthenticationException $e) {
echo "Auth failed: " . $e->getMessage() . "\n";
} catch (HlqueryException $e) {
echo "Error: " . $e->getMessage() . "\n";
} catch (Exception $e) {
echo "Unexpected error: " . $e->getMessage() . "\n";
}

Status Command

The status command provides concise server information:

php example.php status

This will show:

  • Health status
  • Server statistics
  • Protocol codes
  • Server status
  • Root status response

Demo Command

The demo command provides a quick demonstration:

php example.php demo

This will:

  1. Get server stats
  2. Run health check (ping)
  3. Create collection "random_php"
  4. Add a document
  5. List all documents in the collection

Next Steps

  • API Reference - Complete API documentation
  • Tests - Comprehensive test suite
  • Main Example: etc/api/php/example.php - Full example file with all features