Home » Php » php – Check if the index exists or not Elasticsearch

php – Check if the index exists or not Elasticsearch

Posted by: admin July 12, 2020 Leave a comment

Questions:

I want to check in elasticsearch if the index exists or not. If it not exists it should create the index and do other functionality. I try to find out a solution for that, but did not find any perfect solution for that. Can anyone have any solution to solve this problem.

I am using Elasticsearch library.

**$client = new Elasticsearch\Client();**
How to&Answers:

As per index operations and source code the following should work

 $client = new Elasticsearch\Client();
 $indexParams['index']  = 'my_index';   
 $client->indices()->exists($indexParams);

Answer:

This will return true or false:

$params = ['index' => 'products'];
$bool=$client->indices()->exists($params);

Answer:

The documentation for list all indexes here: https://www.elastic.co/guide/en/elasticsearch/reference/current/_list_all_indexes.html

Using curl:

curl 'localhost:9200/_cat/indices?v'

Answer:

Other way by using Facade:

use ScoutElastic\Facades\ElasticClient;

$indexParams['index']  = "model_index";
$exists = ElasticClient::indices()->exists($indexParams);
if ($exists) {
   //do somthing
}