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 tohttps://{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:
- 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:1php -v
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:
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 thevendor
directory’sautoload.php
script:
1 |
- 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:
1 | 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:
1 2 3 4 5 6 7 | $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:
1 2 3 4 5 | $params = [ 'index' => 'some_index', 'type' => 'index_data_type', 'id' => '101' ]; |
1 2 |
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:
1 2 3 4 5 6 7 | $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:
1 | GET /children/child/child3 |
Similarly, that same GET
request, when made using a cURL, also follows the same pattern:
1 | curl -X GET "localhost:9200/children/child/child3?human&pretty" |
The result should look something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 | { "_index" : "children", "_type" : "child", "_id" : "child3", "_version" : 1, "_seq_no" : 0, "_primary_term" : 1, "found" : true, "_source" : { "name" : "Abishai", "age" : 2 } } |
You can use Kibana Dev Tools
to verify the results:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 | $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:
1 2 3 |
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”:
1 2 3 4 5 6 7 8 | GET /children/child/_search { "query" : { "match" : { "age" : 15 } } } |
1 2 3 4 5 6 7 8 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | { "took" : 14, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : 1, "max_score" : 1.0, "hits" : [ { "_index" : "children", "_type" : "child", "_id" : "child1", "_score" : 1.0, "_source" : { "name" : "Raizel", "age" : 15 } } ] } } |
Let look at our results in Kibana’s UI:
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
.
must
is equivalent toAND
.must_not
is equivalent toNOT
.should
is equivalent toOR
.
Let’s look at an example of a query that uses Boolean operators:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $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:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | $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:
1 2 3 4 5 6 7 8 9 10 11 12 13 | GET /children/child/_search { "query" : { "bool" : { "filter" : { "term" : { "gender" : "girl" } }, "must" : { "match" : { "complexion" : "fair" } } } } } |
You can also make an Elasticsearch cURL request using search:
1 2 3 4 5 6 7 8 9 10 11 12 | 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.
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!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started