How To Use The Search API For The Elasticsearch PHP Client

Introduction:

If you’re using Elasticsearch to store documents, you’re going to need to search that data in different ways. Elasticsearch is known for its powerful, efficient search capabilities, and the PHP client for Elasticsearch makes it possible to harness those search capabilities from a PHP script. This step-by-step tutorial will explain how to perform different kinds of queries using the Search API in the PHP client for Elasticsearch. As an alternative, you’ll also learn how to perform an Elasticsearch cURL request using search.

Prerequisites

Before we dive into an example of using the Search API in the PHP client for Elasticsearch, it’s important to make sure certain prerequisites are in place. A few key system requirements include:

  • The Elastic Stack must be properly configured beforehand.
  • Elasticsearch needs to be running. You can check if the service is running by navigating to http://localhost:9200 in a browser, or to https://{YOUR_DOMAIN}:{ELASTICSEARCH_PORT} if you don’t have it installed locally. A JSON response object containing information on the Elasticsearch cluster should load in the webpage:

Elasticsearch JSON Response on port 9200 in a web page:

JSON Response from the Elasticsearch cluster by navigating to port 9200 in a browser

  • The Elasticsearch PHP low-level client needs to be installed and working properly (See Elastic’s official Git repo for the PHP client for more details).
  • This client requires PHP to be installed and working properly. Elastic supports and recommends PHP 7 over earlier versions. You can check the version of PHP running on your server by running the php command in your terminal window. Use the -v option to see a package or module’s version:
    php -v

    Installing PHP 7 on a Linux server

NOTE: Elasticsearch now requires the content-type header option for all cURL requests where a JSON object is in the request body . This change has been in effect since version 6.0 of the Elastic Stack. Be sure to include this option in the header of all your cURL requests passing a JSON object: -H 'Content-Type: application/json'

Without this option, you’ll get a 406 Content-Type header error: Getting a 406 Content-Type Error response after making a cURL HTTP request to Elasticsearch

Connect the PHP script to the low-level Elasticsearch client

Once we’ve confirmed that all the system requirements are in place, we can connect a PHP script to the Elasticsearch client. In our example, we’ll use connection settings that utilize HTTPS. If you plan to utilize HTTP, you just need to change the $hosts array setting to http and port: 9200

  • First, use the PHP require() function to include the vendor directory’s autoload.php script:
 
  • The vendor folder referred to above contains the entire Elasticsearch PHP library that was created by Composer. If this folder is not found in the same directory as your script, then either the low-level client wasn’t installed properly, or Composer was run in a different directory.
  • You can specify the path, or you can use the current working path for the script by appending the __DIR__ constant as shown below:
require __DIR__ . '/vendor/autoload.php'`

Use a PHP array to connect Elasticsearch to the low-level client

Next, we’ll create a PHP associative array containing values that match the Elasticsearch and website domain settings:

$hosts = [
'host' => '{DOMAIN_NAME}',
'port' => '9200',
'scheme' => 'https',
'user' => 'some_user',
'pass' => 'sOmE_cOmPlIcAtEd_PaSsWoRd'
];
  • Make sure the 'scheme' field matches the correct protocol of your domain: either “http” or “https”.
  • Once our $hosts array is properly configured to match the server’s properties, it can be used to create a new Elasticsearch $client instance.

Next, we’ll place the index name and the id of one of its documents into another PHP associative array that can be passed as a parameter to the client instance:

$params = [
'index' => 'some_index',
'type' => 'index_data_type',
'id' => '101'
];
$response = $client->get($params);
print_r($response);

Searching for Documents

At this point, we’ve connected to Elasticsearch, and now we’re ready to search for documents. We’ll do this using the Search API in the PHP client for Elasticsearch. You can search for a document within a specific index via GET or search method. The GET method can be used when you already know the id of the document. On the other hand, search() can be used to search for multiple documents, and it allows you to leverage any field in the document for your query. We’ll look at both methods of searching in the examples that follow.

Using the GET Method to get an Elasticsearch document in PHP

The GET method accepts an array as its argument. This array should consist of index, type and the id of the document you are looking for, as shown in the example below:

$params = [
'index' => 'children',
'type' => 'child',
'id' => 'child3'
];

$results = $client->get($params);

The $params associative array, which is used to make API calls to Elasticsearch in PHP, maps perfectly to the HTTP requests made in the Kibana Console:

GET /children/child/child3

Similarly, that same GET request, when made using a cURL, also follows the same pattern:

curl -X GET "localhost:9200/children/child/child3?human&pretty"

The result should look something like this:


GeSHi Error: GeSHi could not find the language json (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)

You can use Kibana Dev Tools to verify the results:

A simple GET request in the Kibana Console UI

Search with Specific Fields via Match Query

While the examples shown above work well when you know the id of the document you’re looking for, there are many situations where you may not know the id, but you do have certain search criteria in mind. In the PHP client library, the _search query is included as a built-in method. Just like in a cURL or Kibana console _search request, making a call to the search method in the PHP client requires an index, type and a body keys to be passed as array arguments. The body key itself is actually another nested array where the “body” of the query is specified:

$params = [
'index' => 'children',
'type' => 'child',
'body' => [
'query' => [
'match' => [
'age' => '15'
// return all documents that match
// the specified age of 15
]
]
]
];

Let’s pass that entire nested associative array to the search method, and have it return a result:

$result = $client->search($params);
// print the results of the API call
var_dump(result);

The script shown above is also similar to the Kibana request, with just a few differences in syntax. Instead of the colons used in a JSON object, a PHP array uses => to change the value of a key or “field”:

GET /children/child/_search
{
"query" : {
"match" : {
"age" : 15
}
}
}
curl -XGET 'localhost:9200/children/child/_search?human&pretty' -H 'Content-Type: application/json' -d '
{
"query" : {
"match" : {
"age" : 15
}
}
}'

The result should look something like this:


GeSHi Error: GeSHi could not find the language json (using path /nas/content/live/orkbprod/wp-content/plugins/codecolorer/lib/geshi/) (code 2)

Let look at our results in Kibana’s UI:

Making a GET search request in Kibana that matches a certain age

Search via Bool Queries

You can also add Boolean operators, such as AND, OR and NOT to refine search queries and provide more relevant, specific results. Instead of these traditional operators, the Search API for the PHP client uses the operators must, must_not and should.

  1. must is equivalent to AND.
  2. must_not is equivalent to NOT.
  3. should is equivalent to OR.

Let’s look at an example of a query that uses Boolean operators:

$params = [
'index' => 'children',
'type' => 'child',
'body' => [
'query' => [
'bool' => [
'must' => [
[ 'match' => [ 'gender' => 'girl' ] ],
[ 'match' => [ 'age' => 2 ] ],
]
]
]
]
];

$results = $client->search($params);

echo '
'
; print_r($results); echo '
'
; // echo the $result

You results should look something like this:

Array results

More Elasticsearch Boolean Queries in PHP

The previous example showed a fairly simple example of a Boolean query. Our next example depicts a more complicated form of the Boolean query that contains both a filter and a query.

$params = [
'index' => 'children',
'type' => 'child',
'body' => [
'query' => [
'bool' => [

'filter' => [
'term' => [ 'complexion' => 'fair' ]
],
'should' => [
[ 'match' => [ 'gender' => 'girl' ] ],

]
]
]
]
];

$results = $client->search($params);

echo '
'
; print_r($results); echo '
'
; // To display the records in a readable manner

The GET command shown below is the equivalent of the query depicted in the above PHP script:

GET /children/child/_search
{
"query" : {
"bool" : {
"filter" : {
"term" : { "gender" : "girl" }
},
"must" : {
"match" : { "complexion" : "fair" }
}
}
}
}

You can also make an Elasticsearch cURL request using search:

curl -XGET 'localhost:9200/children/child/_search?human&pretty' -H 'Content-Type: application/json' -d '{
"query" : {
"bool" : {
"filter" : {
"term" : { "gender" : "girl" }
},
"should" : {
"match" : { "complexion" : "fair" }
}
}
}
}'

The result should look something like this.

PHP Array response from an Elasticsearch GET call

Conclusion

There’s no doubt that Elasticsearch is known for its fast and powerful search capabilities. With the Elasticsearch client library for PHP, you can harness the full power of Elasticsearch in your PHP scripts. Using the instructions provided in this article, you should have no trouble finding the documents you need using the Search API in the PHP client for Elasticsearch.

Pilot the ObjectRocket platform free for 30 Days

It's easy to get started. Imagine the time you'll save by not worrying about database management. Let's do this!

PILOT FREE FOR 30 DAYS

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.