Querying an Elasticsearch Server using PHP - Quick Tutorial + Examples
Last updated:Elasticsearch is a full-text search engine based on Apache Lucene.
It provides an official API for a couple of languages, PHP included.
In order to install the Official PHP Client, composer is the best way to go. If you already use composer in your project, add this to composer.json
:
"require": {
"elasticsearch/elasticsearch": "~1.0"
},
Examples from here on assume you have an Elasticsearch server listening on http://localhost:9200
Creating an Index
An index is the container for your data.
<?php
//instantiating the client
$client = new Elasticsearch\Client(['hosts'=>'localhost:9200']);
//setting some default options
$params = [];
$params['index'] = 'my_first_index';
$params['body']['settings']['number_of_shards'] = 3;
$params['body']['settings']['number_of_replicas'] = 2;
//create the actual index
$client->indices()->create($indexingParams);
Indexing a document
A document is just an array of name-value pairs. Like a Python dictionary, a Ruby Hash, a PHP associative array or a JSON object.
Indexing is the act of adding a document to your index.
($client
is the client as created in the previous example)
<?php
$indexParams = [];
$indexParams['index'] = 'my_first_index';
$indexParams['type'] = 'my_first_type';
// in case there's an error, PHP doesn't hang
$indexParams['timeout'] = 2000;
// this is an advanced feature we don't need right now
$indexParams['consistency'] = 'one';
//let's index a generic person object (i.e. a PHP array)
$obj = [];
$obj['name'] = 'john';
$obj['age'] = '20';
$obj['job'] = 'clerk';
//now you add your obj to the params
$indexParams['body'] = $obj;
//and index it
$client->index($indexParams);
Making a Query
In this example, we'll use the $client
we've created in the first step and submit a query using that.
<?php
$searchParams = [];
$searchParams['index'] = 'my_first_index';
$searchParams['type'] = 'my_first_type';
// this is how you specify a query in ES
$searchParams['body']['query']['match']['_all'] = 'my_query';
//default sorting: _score descending (score is a simple relevance metric)
$searchParams['body']['sort'] = ['_score'];
// the actual query. Results are stored in a PHP array
$retDoc = $client->search($searchParams);
References and Observations
- There's also Elastica - another Elasticsearch client which has seen some use by the community use as well. I didn't use it yet so I have no opinion on whether it's better or worse than the official client I'm using.