X
    Categories: Learn PHP Tutorials, Tips And GuidesYii Tutorials, Tips And Guides for beginners

How to Configure Search With Elasticsearch in Yii 2

In this tutorial, I will discuss how to search data in Elasticsearch in Yii2. In order to properly test the code, Elasticsearch database must have some sample data. To learn how you could add sample data, please refer to my previous article. For this demonstration, the sample data consists of articles on different topics.

Let’s get started by creating a new model that will be used for searching the data. The name of the model is Search.

Related: How To Host Yii 2 Framework On Cloudways Using Composer

Step 1: Creating Model for Search

The Search model extends from Elastic model which I created in the previous article. Now paste the following code in it.

<?php

namespace app\models;

use app\models\Elastic;

use yii\base\Model;

use yii\elasticsearch\ActiveDataProvider;

use yii\elasticsearch\Query;

use yii\elasticsearch\QueryBuilder;

/**

* ArticlesSearch represents the model behind the search form about `app\models\Articles`.

*/

class Search extends Elastic

{

   public function Searches($value)

   {

       $searchs      = $value['search'];

       $query        = new Query();

       $db           = Elastic::getDb();

       $queryBuilder = new QueryBuilder($db);

       $match   = ['match' => ['article_content' =>$searchs]];

       $query->query = $match;

       $build        = $queryBuilder->build($query);

       $re           = $query->search($db, $build);

       $dataProvider = new ActiveDataProvider([

           'query'      => $query,

           'pagination' => ['pageSize' => 10],

       ]);

       return $dataProvider;

   }

}

Let’s understand the above code.

I started with Elasticsearch Query Methods that come with Yii2 Elasticsearch extension and combined it with QueryBuilder to build the search query that searches for the content inside the body of the article.

Next, I send the query for search with search() method. The method returns the result inside a dataprovider. To know more about the search in Elasticsearch, please go here.

Step 2: Updating the Controller of Elasticsearch

Now let’s update the controller of Elasticsearch. I will use the same controller that was used in the previous article.

First, actionIndex needs to be updated, so that it can render an index page with a form for search. The update will also create a new action actionSearch, and that will search user queries in Elasticsearch database.

Replace the controller code with the following:

<?php
namespace app\controllers;

use app\models\search;
use Yii;
use yii\web\Controller;

class ElasticController extends Controller
{

    public function actionIndex()
    {

        return $this->render('index');

    }

    public function actionSearch()
    {

        $elastic = new Search();
        $result  = $elastic->Searches(Yii::$app->request->queryParams);
        $query = Yii::$app->request->queryParams;
        return $this->render('search', [
            'searchModel'  => $elastic,
            'dataProvider' => $result,
            'query'        => $query['search'],
        ]);

    }

}

Step 3: Creating Views for Search

Now go to your views folder, create a new folder and name it elastic.

First, create an index page for it. Create a new file inside elastic folder and name it index.php. Paste the following code in it:

<?php
use yii\bootstrap\ActiveForm;
use yii\helpers\Html;
?>
<?php $form = ActiveForm::begin([
    'action'  => ['search'],
    'method'  => 'get',
    'options' => ['class' => 'form-inline'],
]);?>
<div class="form-group">

  <label class="control-label" >
The active form page will look something like this.



Now, let’s create a page which will show the search results. Create a new file in elastic folder and name it search.php. Paste the following code in it:
<?php

use yii\helpers\BaseStringHelper;
$this->title = 'Search';
?>
<div class="container-fluid">
<h1>Search Result for <?php echo "<span class='label label-success'>" . $query . "</span>" ?></h1>
<?php
$result = $dataProvider->getModels();

foreach ($result as $key) {

    echo "<div class='row'>";

    echo "<div class='panel panel-default'>";
    foreach ($key['_source'] as $key => $value) {

        



        
if ($key == "article_name") {
            echo "<div class='panel-heading'>" . $value . "</div>";
        }
        if ($key == "article_content") {
            echo "<div class='panel-body'>" . BaseStringHelper::truncateWords($value, 50, '...', true) . "<br>";
        }
        if ($key == "category_name") {
            echo "<span class='label label-success'>" . $value . "</span></div>";
        }
        


   }
    echo "</div>";
    echo "</div>";

}?>

</div>

The hard work is now over! It is now time to see the code in action!

Related: How To Setup Elasticsearch With MySQL

Step 4: Searching in Elasticsearch

To check the code, first route the Yii site to elastic/index.

Next, search something in it.

The result page would resemble:

Conclusion

In this article, I have discussed how to build and use search query inside Elasticsearch using Yii2. If you need clarifications or would like to contribute to the discussion, please leave a comment below

Ahmed Khan: Ahmed was a PHP community expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is a software engineer with extensive knowledge in PHP and SEO. He loves watching Game of Thrones is his free time. Follow Ahmed on Twitter to stay updated with his works. You can email him at ahmed.khan@cloudways.com