PHP client

The OpenSearch PHP client provides a safer and easier way to interact with your OpenSearch cluster. Rather than using OpenSearch from the browser and potentially exposing your data to the public, you can build an OpenSearch client that takes care of sending requests to your cluster.

The client contains a library of APIs that let you perform different operations on your cluster and return a standard response body. The example here demonstrates some basic operations like creating an index, adding documents, and searching your data.

Setup

To add the client to your project, install it using composer:

  1. composer require opensearch-project/opensearch-php

To install a specific major version of the client, run the following command:

  1. composer require opensearch-project/opensearch-php:<version>

Then require the autload file from composer in your code:

  1. require __DIR__ . '/vendor/autoload.php';

Sample code

  1. <?php
  2. require __DIR__ . '/vendor/autoload.php';
  3. $client = (new \OpenSearch\ClientBuilder())
  4. ->setHosts(['https://localhost:9200'])
  5. ->setBasicAuthentication('admin', 'admin') // For testing only. Don't store credentials in code.
  6. ->setSSLVerification(false) // For testing only. Use certificate for validation
  7. ->build();
  8. $indexName = 'test-index-name';
  9. // Print OpenSearch version information on console.
  10. var_dump($client->info());
  11. // Create an index with non-default settings.
  12. $client->indices()->create([
  13. 'index' => $indexName,
  14. 'body' => [
  15. 'settings' => [
  16. 'index' => [
  17. 'number_of_shards' => 4
  18. ]
  19. ]
  20. ]
  21. ]);
  22. $client->create([
  23. 'index' => $indexName,
  24. 'id' => 1,
  25. 'body' => [
  26. 'title' => 'Moneyball',
  27. 'director' => 'Bennett Miller',
  28. 'year' => 2011
  29. ]
  30. ]);
  31. // Search for it
  32. var_dump(
  33. $client->search([
  34. 'index' => $indexName,
  35. 'body' => [
  36. 'size' => 5,
  37. 'query' => [
  38. 'multi_match' => [
  39. 'query' => 'miller',
  40. 'fields' => ['title^2', 'director']
  41. ]
  42. ]
  43. ]
  44. ])
  45. );
  46. // Delete a single document
  47. $client->delete([
  48. 'index' => $indexName,
  49. 'id' => 1,
  50. ]);
  51. // Delete index
  52. $client->indices()->delete([
  53. 'index' => $indexName
  54. ]);