Magento, Magento 2

How to Check Elasticsearch is Enabled Programmatically in Magento 2

How to Check Elasticsearch is Enabled Programmatically in Magento 2

In this tutorial, Today I will explain how to check Elasticsearch is enabled or not programmatically in Magento 2. After Magento 2.3.x, It provides a third-party search engine which is Elastic Search. Now, if you want to develop some functionality based on elastic search enabled or not then, how can you check that elastic search enabled or not.

So, Let’s follow the below step for that. \Magento\Elasticsearch\Model\Config::isElasticsearchEnabled() this function return that elastic search enabled or not.

You may also like this :

First of all, You need to inject \Magento\Elasticsearch\Model\Config class in your construct. Then, Add this below code in your block file :

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Block;

class Helloworld extends \Magento\Framework\View\Element\Template
{
    protected $elasticConfig;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Elasticsearch\Model\Config $elasticConfig,
        array $data = []
    ) {
        $this->elasticConfig = $elasticConfig;
        parent::__construct($context, $data);
    }

    public function isEnabled()
    {
        return $this->elasticConfig->isElasticsearchEnabled();
    }
}

Now, you can call the isEnabled() function in your phtml or any other file it will return a boolean value.

However, To enable elastic search from the configuration,

Go to Admin -> Store -> Configuration -> Catalog -> Catalog -> Catalog Search -> Search Engine

That’s it !!!

I hope this blog is easy to understand how to check Elasticsearch is enabled or not programmatically in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with a proper solution.

Stay Safe and Stay Connected !!

Tagged , ,