Search Engine with PHP & Elasticsearch

elasticsearch-logo

In this tutorial, we’re going to take a look at Elasticsearch and how we can use it in PHP. ElasticSearch is an open-source and distributed search engine which is very much scalable. We can use it to perform fast full-text and other complex searches. It also includes a REST API which allows us to easily issue requests for creating, deleting, updating and retrieving of data. You can read about Elastic Search at: https://www.elastic.co/products/elasticsearch

Installing Elasticsearch

Download ElasticSearch from https://www.elastic.co/downloads/elasticsearch. This tutorial will assume you’re using a Windows environment. For Windows – it’s a Zip file – one can extract it into C:\elasticsearch-2.2.0\.

Now Let’s Test
1. In Windows Environment, start command line and cd C:\elasticsearch-2.2.0\bin
2. Now execute elasticsearch.bat
3. Now test it in your browser

When we access http://localhost:9200 in the browser, we get something similar to the following:

{
  "name" : "Marvin Flumm",
  "cluster_name" : "elasticsearch",
  "version" : {
    "number" : "2.2.0",
    "build_hash" : "8ff36d139e16f8720f2947ef62c8167a888992fe",
    "build_timestamp" : "2016-01-27T13:32:39Z",
    "build_snapshot" : false,
    "lucene_version" : "5.4.1"
  },
  "tagline" : "You Know, for Search"
}

Using Elasticsearch

Now we can start playing with Elasticsearch. First, let’s install the official Elasticsearch client for PHP.

Installation via Composer. The recommended method to install Elasticsearch-PHP is through Composer.

For more information refer https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/_installation_2.html

Next, let’s create a new php file that we will use for testing and with the following code so that we can use the Elasticsearch client.

require 'vendor/autoload.php';
$client = Elasticsearch\ClientBuilder::create()->build();

Indexing a Document

To index a document, we need to specify four pieces of information: index, type, id and a document body. This is done by constructing an associative array of key:value pairs. The request body is itself an associative array with key:value pairs corresponding to the data in your document:

$params = array();
$params['body']  = array('title' => 'title of the article','body' => 'add content here for your article','keywords' => 'key1,key2');
$params['index'] = 'articles';
$params['type']  = 'article';
$params['id']    = '1';
$response = $client->index($params);
print_r($response);

If you print out the $result you get something similar to the following:

Array
(
    [_index] => articles
    [_type] => article
    [_id] => 1
    [_version] => 1
    [_shards] => Array
        (
            [total] => 2
            [successful] => 1
            [failed] => 0
        )

    [created] => 1
)

Get a Document

Let’s get the document that we just indexed. This will simply return the document:

$params = [
    'index' => 'articles',
    'type' => 'article',
    'id' => '1'
];

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

The response contains some metadata (index, type, etc) as well as a _source field…this is the original document that we sent to Elasticsearch.

Array
(
    [_index] => articles
    [_type] => article
    [_id] => 1
    [_version] => 7
    [found] => 1
    [_source] => Array
        (
            [title] => title of the article
            [body] => add content here for your article
            [keywords] => key1,key2
        )

)

Search for a document

The array argument for the search method needs to have the index, the type and the body keys. The body is where we specify the query. To start, here’s an example on how we use it to return all the documents

$params = [
    'index' => 'articles',
   'type' => 'article',
    'body' => [
        'query' => [
			'bool' => [
				'should' => [
					['match' => ['keywords' => 'key2']],
					['match' => ['title' => 'key2']],
					['match' => ['body' => 'key2']],
				]
			]
        ]
    ]
];

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

This returns the following:

Array
(
    [took] => 3
    [timed_out] => 
    [_shards] => Array
        (
            [total] => 5
            [successful] => 5
            [failed] => 0
        )

    [hits] => Array
        (
            [total] => 1
            [max_score] => 0.028130025
            [hits] => Array
                (
                    [0] => Array
                        (
                            [_index] => articles
                            [_type] => article
                            [_id] => 1
                            [_score] => 0.028130025
                            [_source] => Array
                                (
                                    [title] => title of the article
                                    [body] => add content here for your article
                                    [keywords] => key1,key2
                                )

                        )

                )

        )

)

Updating a Document

If you want to partially update a document (e.g. change an existing field, or add a new one) you can do so by specifying the doc in the body parameter. This will merge the fields in doc with the existing document

$params = [
    'index' => 'articles',
    'type' => 'article',
    'id' => '1',
    'body' => [
        'doc' => [
            'new_field' => 'abc',
			'title' => 'update title'
        ]
    ]
];

$result = $client->update($params);

Delete a document

Deleting a document can be done by calling the delete method. This method accepts an array containing the index, type and id as its argument.

$params = array();
$params['index'] = 'articles';
$params['type'] = 'article';
$params['id'] = '1';

$result = $client->delete($params);

Conclusion
In this article, we looked at how we can work with Elasticsearch in PHP using the official Elasticsearch client. Elasticsearch is a nice way to add search functionality to your PHP applications. It supports realtime time indexing and full text search.

Please see link for more information on Elasticsearch-PHP

Advertisements

2 thoughts on “Search Engine with PHP & Elasticsearch

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s