This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

How to Configure Search With Elasticsearch in Yii 2

Updated on September 25, 2021

4 Min Read
configuring elasticsearch

Elasticsearch is a highly scalable full-text search. It permits you to store, search, and analyze large volumes of information rapidly. It is majorly used as the basic engine that powers applications that have complex look features and requirements.

Elasticsearch gives a disseminated framework on beat of Lucene StandardAnalyzer for ordering and programmed sort speculating and utilizes a JSON-based REST API to allude to Lucene features.

In this piece, I will discuss how to configure ElasticSearch in Yii2. In order to properly test the code, Elasticsearch database must have some sample data. To learn how you canould 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.

Step 1: Creating Model for Search

Before we configure ElasticSearch, we need to extend the Search model from the Elastic model that 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 the 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.

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Step 2: Updating the Controller of Elasticsearch

Now you need to 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 the 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" for="search">Search: </label>


  <input id="search" name="search" placeholder="Search Here" class="form-control input-md" required value="" type="text">

</div>

      <div class="form-group">
        <?=Html::submitButton('Search', ['class' => 'btn btn-primary'])?>

    </div>

    <?php ActiveForm::end();?>

The active form page will look something like this.

image01

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

 

Search Result for

 

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

Step 4: Searching in Elasticsearch

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

Next, search for something in it.

image00

The result page would resemble:

result page javascript

Conclusion

Elasticsearch is a disseminated, Restful and analytics search engine capable of solving a wide variety of problems. Many ventures are leaning towards using ElasticSearch and integrating it in their current backend framework.

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.

Q. What is Elasticsearch configuration ?

A: Elasticsearch configures the JVM to compose lethal error logs to the default logging directory. On RPM and Debian bundles, this registry is /var/log/elasticsearch. On Linux and MacOS and Windows distributions, the logs directory is found under the root of the Elasticsearch installation.

Q. How do I set up Elasticsearch locally?

A: 1. Run Elasticsearch.
2. Extract the archive: macOS, Linux or windows.
3. Execute the Elasticsearch from the bin directory.
4. Run two more instances of Elasticsearch so you can analyze how a typical multi-node cluster works.
5. Run the cat health API to verify that your cluster is running.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Inshal Ali

Inshal is a Content Marketer at Cloudways. With background in computer science, skill of content and a whole lot of creativity, he helps business reach the sky and go beyond through content that speaks the language of their customers. Apart from work, you will see him mostly in some online games or on a football field.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now