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();**
As per index operations and source code the following should work
$client = new Elasticsearch\Client();
$indexParams['index'] = 'my_index';
$client->indices()->exists($indexParams);
This will return true or false:
$params = ['index' => 'products'];
$bool=$client->indices()->exists($params);
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'
Other way by using Facade:
use ScoutElastic\Facades\ElasticClient;
$indexParams['index'] = "model_index";
$exists = ElasticClient::indices()->exists($indexParams);
if ($exists) {
//do somthing
}
I was able to do it with node.js, as below
const { Client } = require('@elastic/elasticsearch');
const client = new Client({
node: ES_URL,
});
await client.indices.exists({ index: 'INDEX_NAME' });
and the response should be similar to this one below:
{
body: true,
statusCode: 200,
headers: {
date: 'Sun, 07 Mar 2021 13:07:31 GMT',
server: 'Apache/2.4.46 (Unix) OpenSSL/1.1.1d',
'content-type': 'application/json; charset=UTF-8',
'content-length': '2796',
'keep-alive': 'timeout=5, max=100',
connection: 'Keep-Alive'
},
meta: {
context: null,
request: { params: [Object], options: {}, id: 1 },
name: 'elasticsearch-js',
connection: {
url: 'ES_URL',
id: 'ES_ID',
headers: {},
deadCount: 0,
resurrectTimeout: 0,
_openRequests: 0,
status: 'alive',
roles: [Object]
},
attempts: 0,
aborted: false
}
}
For more recent versions of Elasticsearch (8.x), using the php library (with corresponding version 8.x) a call to $client->indices()->exists($indexParams)
no longer returns a boolean, it instead returns an instance of Elastic\Elasticsearch\Response\Elasticsearch
. This response is actually a 200 HTTP response if the index exists, or a HTTP 404 if it does not, but it also has the helpful asBool()
you can use that abstracts away the HTTP codes eg
$client->indices()->exists($indexParams)->asBool();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.