A PHP adapter for the OpenSearch PHP client.
Install the package with Composer:
composer require directorytree/opensearch-adapterCreate the adapter managers from an OpenSearch\Client instance:
use DirectoryTree\OpenSearchAdapter\Documents\DocumentManager;
use DirectoryTree\OpenSearchAdapter\Indices\IndexManager;
use OpenSearch\Client;
$documents = new DocumentManager($client);
$indices = new IndexManager($client);Use an index blueprint when you want fluent mapping and settings builders:
use DirectoryTree\OpenSearchAdapter\Indices\IndexBlueprint;
use DirectoryTree\OpenSearchAdapter\Indices\Mapping;
use DirectoryTree\OpenSearchAdapter\Indices\Settings;
$mapping = (new Mapping)
->keyword('id')
->text('title')
->object('author', [
'properties' => [
'name' => ['type' => 'text'],
],
]);
$settings = (new Settings)->index([
'number_of_shards' => 1,
'number_of_replicas' => 0,
]);
$indices->create(new IndexBlueprint('books', $mapping, $settings));Raw OpenSearch arrays are supported when you already have a mapping or settings payload:
$indices->createRaw(
'books',
mapping: [
'properties' => [
'title' => ['type' => 'text'],
],
],
settings: [
'index' => [
'number_of_shards' => 1,
],
],
);Documents contain the OpenSearch document ID and source payload:
use DirectoryTree\OpenSearchAdapter\Documents\Document;
$documents->index('books', [
new Document('1', [
'title' => 'The Hobbit',
]),
]);Routing values can be attached by document ID:
use DirectoryTree\OpenSearchAdapter\Documents\Routing;
$routing = (new Routing)->add('1', 'tenant-1');
$documents->index('books', [
new Document('1', [
'title' => 'The Hobbit',
]),
], routing: $routing);Build a search request with raw OpenSearch query fragments:
use DirectoryTree\OpenSearchAdapter\Search\SearchRequest;
$request = (new SearchRequest([
'match' => [
'title' => 'hobbit',
],
]))
->size(10)
->highlight([
'fields' => [
'title' => new stdClass,
],
]);
$response = $documents->search('books', $request);
$total = $response->total();
$hits = array_map(
fn ($hit) => $hit->document()->content(),
$response->hits(),
);Aliases can include optional filters and routing values:
use DirectoryTree\OpenSearchAdapter\Indices\Alias;
$indices->putAlias('books', new Alias(
'tenant-books',
filter: [
'term' => [
'tenant_id' => 1,
],
],
routing: 'tenant-1',
));
$aliases = $indices->getAliases('books');Search response objects expose the original OpenSearch payload through raw():
$rawHit = $response->hits()[0]->raw();
$rawResponse = $response->raw();