PHP

Getting Elasticsearch up and running with a PHP app is fairly straightforward. We recommend using the official PHP client, as it is being actively developed alongside Elasticsearch.

Adding the Elasticsearch library

Like Heroku, we recommend Composer for dependency management in PHP projects, so you’ll need to add the Elasticsearch library to your composer.json file:

{
    "require": {
        "elasticsearch/elasticsearch": "1.0"
    }
}

Heroku will automatically add the library when you deploy your code.

Using the library

The elasticsearch-php library is configured almost entirely by associative arrays. To initialize your client, use the following code block:

// Initialize the parameters for the cluster
$params = array();
$params['hosts'] = array (
    getenv("BONSAI_URL"),
);

$client = new Elasticsearch\Client($params);

Note that the host is pulled from the environment. When you add Bonsai to your app, the cluster will be automatically created and a BONSAI_URL variable will be added to your environment. The initialization process above allows you to access your cluster without needing to hardcode your authentication credentials.

Indexing your documents

Bonsai does not support lazy index creation, so you will need to create your index before you can send over your documents. You can specify a number of parameters to configure your new index; the code below is the minimum needed to get started:

$indexParams = array();
$indexParams['index']  = 'my_index';    //index

$client->indices()->create($indexParams);

Once your index has been created, you can add a document by specifying a body (an associative array of fields and data), target index, type and (optionally) a document ID. If you don’t specify an ID, Elasticsearch will create one for you:

$params['body']  = array('testField' => 'abc');

$params['index'] = 'my_index';
$params['type']  = 'my_type';
$params['id']    = 'my_id';

// Document will be indexed to my_index/my_type/my_id
$ret = $client->index($params);