Executing a ping query on Solr using PHP
Ping queries are used in Solr to monitor the health of the Solr server. Let us first see how the ping query works on the Solr Admin web interface:
Open up the browser and go to the URL for Solr.
Select collection1 from the dropdown on the left-hand side panel.
Click on Ping and you will see the ping time in milliseconds appear next to the ping's link. Our ping is working fine.
Let us check the version of PHP installed. We need Version 5.3.2 and above. To check the version, run php –v
on the Windows or Linux command line as follows:
c:\>php -v PHP 5.4.16 (cli) (built: Jun 5 2013 21:01:46) Copyright (c) 1997-2013 The PHP Group Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies
To get ping working from our PHP code, we will need a utility called cURL. For Linux environments, we need to install the curl
, libcurl
, and php5-curl
packages. On Ubuntu distribution of Linux it can be installed using the following command:
sudo apt-get install curl php5-curl
For enabling cURL on windows, we need to edit the php.ini
file in our PHP installation. Search for the extensions directory setting and change it to where php_curl.dll
is located. Also, uncomment the line which loads php_curl.dll
:
extension=php_curl.dll extension_dir = "C:\php\ext"
The following URL is the URL that is being called for executing the ping query. On going to this URL, we can see the response that contains the response header and the status, which is OK.
http://localhost:8080/solr/collection1/admin/ping
We can see that the response is in XML. To convert the response to JSON, simply add wt=json
to the earlier URL:
http://localhost:8080/solr/collection1/admin/ping/?wt=json
Linux users can check the response of a curl call using the following command:
curl http://localhost:8080/solr/collection1/admin/ping/?wt=json {"responseHeader":{"status":0,"QTime":7,"params":{"df":"text","echoParams":"all","rows":"10","echoParams":"all","wt":"json","q":"solrpingquery","distrib":"false"}},"status":"OK"}
A direct call to Solr via PHP requires us to call the ping with a JSON response URL via cURL and decode the JSON response to show the result. Here is a piece of code to do the same. This code can be executed using the PHP command line:
$curl = curl_init("http://localhost:8080/solr/collection1/admin/ping/?wt=json"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); $data = json_decode($output, true); echo "Ping Status : ".$data["status"]."\n";
On executing the preceding code via command line, we will get the output as follows:
Ping Status : OK
Tip
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.