How to Configure Elasticsearch for Magento 2 on the Command Line (CLI)

Magento introduced Elasticsearch as a hard dependency in Magento 2.4. This first release misses Magento command line options for Elasticsearch configuration. This article explains how you can configure Elasticsearch for Magento 2 from the command line.

M2 Fresh install with Elasticsearch

When you use the installer you can pass Elasticsearch configuration variables. You do this by passing the extra --elasticsearch- parameters to the magento setup:install command.

bin/magento setup:install
  [add all standard parameters here]
  --elasticsearch-host localhost \
  --elasticsearch-port 9200 \
  --elasticsearch-enable-auth 1 \
  --elasticsearch-username "$eluser" \
  --elasticsearch-password "$elpassword" \
  --elasticsearch-index-prefix "${eluser}.magento2" \

Replace $eluser and $elpassword in the above example with your Elasticsearch credentials.

This is however a bit more troublesome when upgrading an existing installation that has no Elasticsearch configured. If you upgrade from earlier versions of Magento, and were not using Elasticsearch from before, you will likely run into issues while upgrading. This is because Magento won’t be able to find Elasticsearch.

Error: Could not validate a connection to Elasticsearch. null

If you get this error while trying to upgrade, it means Magento could not connect to your Elasticsearch instance. The common reason is that you have not been using it before, and it just is not configured.

We usually configure Magento by running  magerun2 setup:config:set. If we list the options in Magento 2.4 for this command, it is clear that Elasticsearch is not yet supported here (Amap, Redis, Sessions, Caching etc is supported).

To configure Elasticsearch from the command line, run the following commands – replacing USERNAME, PASSWORD and PREFIX with the correct information for your instance.

$ magerun2 config:set catalog/search/elasticsearch7_server_hostname localhost
$ magerun2 config:set catalog/search/elasticsearch7_enable_auth 1
$ magerun2 config:set catalog/search/elasticsearch7_username USERNAME
$ magerun2 config:set catalog/search/elasticsearch7_password PASSWORD
$ magerun2 config:set catalog/search/elasticsearch7_index_prefix USERNAME.magento2

After this, you should be able to run magerun2 setup:upgrade without issues. Servebolt offers more command line solutions for Magento. You can earn more about our Magento tools here.