¿lista todos los índices en ElasticSearch server?


Me gustaría listar todos los índices presentes en un servidor ElasticSearch. Probé esto:

curl -XGET localhost:9200/

Pero solo me da esto:

{
  "ok" : true,
  "status" : 200,
  "name" : "El Aguila",
  "version" : {
    "number" : "0.19.3",
    "snapshot_build" : false
  },
  "tagline" : "You Know, for Search"
}

Quiero una lista de todos los índices..

Author: Eva, 2013-07-02

16 answers

Para obtener una lista concisa de todos los índices de su clúster, llame a

curl http://localhost:9200/_aliases

Esto le dará una lista de índices y sus alias.

Si lo quieres bastante impreso, agrega pretty=1:

curl http://localhost:9200/_aliases?pretty=1

El resultado se verá algo como esto, si sus índices se llaman old_deuteronomy y mungojerrie:

{
  "old_deuteronomy" : {
    "aliases" : { }
  },
  "mungojerrie" : {
    "aliases" : {
      "rumpleteazer" : { },
      "that_horrible_cat" : { }
    }
  }
}
 302
Author: karmi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-16 11:27:48

Intenta

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

Te daré la siguiente salida auto explicativa en forma tabular

health index    pri rep docs.count docs.deleted store.size pri.store.size
yellow customer   5   1          0            0       495b           495b
 40
Author: Abhijit Mazumder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-13 19:59:55

Puede consultar localhost:9200/_status y eso le dará una lista de índices e información sobre cada uno. La respuesta se verá algo como esto:

{
  "ok" : true,
  "_shards" : { ... },
  "indices" : {
    "my_index" : { ... },
    "another_index" : { ... }
  }
}
 31
Author: Matthew Boynes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-02 14:07:05

El comando _stats proporciona formas de personalizar los resultados especificando las métricas deseadas. Para obtener los índices la consulta es la siguiente:

GET /_stats/indices

El formato general de la consulta _stats es:

/_stats
/_stats/{metric}
/_stats/{metric}/{indexMetric}
/{index}/_stats
/{index}/_stats/{metric}

Donde las métricas son:

indices, docs, store, indexing, search, get, merge, 
refresh, flush, warmer, filter_cache, id_cache, 
percolate, segments, fielddata, completion

Como un ejercicio para mí, he escrito un pequeño plugin de elasticsearch que proporciona la funcionalidad para listar índices de elasticsearch sin ninguna otra información. Lo puedes encontrar en las siguientes url:

Http://blog.iterativ.ch/2014/04/11/listindices-writing-your-first-elasticsearch-java-plugin/

Https://github.com/iterativ/elasticsearch-listindices

 25
Author: paweloque,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-29 05:02:28

Uso esto para obtener todos los índices:

$ curl --silent 'http://127.0.0.1:9200/_cat/indices' | cut -d\  -f3

Con esta lista puedes trabajar...

Ejemplo

$ curl -s 'http://localhost:9200/_cat/indices' | head -5
green open qa-abcdefq_1458925279526           1 6       0     0   1008b    144b
green open qa-test_learnq_1460483735129    1 6       0     0   1008b    144b
green open qa-testimportd_1458925361399       1 6       0     0   1008b    144b
green open qa-test123p_reports                1 6 3868280 25605   5.9gb 870.5mb
green open qa-dan050216p_1462220967543        1 6       0     0   1008b    144b

Para obtener la 3a columna de arriba (nombres de los índices):

$ curl -s 'http://localhost:9200/_cat/indices' | head -5 | cut -d\  -f3
qa-abcdefq_1458925279526
qa-test_learnq_1460483735129
qa-testimportd_1458925361399
qa-test123p_reports
qa-dan050216p_1462220967543

NOTA: También puede usar awk '{print $3}' en lugar de cut -d\ -f3.

Encabezados de columna

También puede sufijar la consulta con un ?v para agregar un encabezado de columna. Al hacerlo, romperá el método cut..., por lo que recomendaría usar la selección awk.. en este punto.

$ curl -s 'http://localhost:9200/_cat/indices?v' | head -5
health status index                              pri rep docs.count docs.deleted store.size pri.store.size
green  open   qa-abcdefq_1458925279526             1   6          0            0      1008b           144b
green  open   qa-test_learnq_1460483735129      1   6          0            0      1008b           144b
green  open   qa-testimportd_1458925361399         1   6          0            0      1008b           144b
green  open   qa-test123p_reports                  1   6    3868280        25605      5.9gb        870.5mb
 13
Author: themisterunknown,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-13 13:10:41

También recomendaría hacer /_cat/indices que da una buena lista legible por humanos de sus índices.

 9
Author: Matt Watson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-07 18:53:21

curl -XGET 'http://localhost:9200/_cluster/health?level=indices'

Esto producirá como abajo

{
  "cluster_name": "XXXXXX:name",
  "status": "green",
  "timed_out": false,
  "number_of_nodes": 3,
  "number_of_data_nodes": 3,
  "active_primary_shards": 199,
  "active_shards": 398,
  "relocating_shards": 0,
  "initializing_shards": 0,
  "unassigned_shards": 0,
  "delayed_unassigned_shards": 0,
  "number_of_pending_tasks": 0,
  "number_of_in_flight_fetch": 0,
  "task_max_waiting_in_queue_millis": 0,
  "active_shards_percent_as_number": 100,
  "indices": {
    "logstash-2017.06.19": {
      "status": "green",
      "number_of_shards": 3,
      "number_of_replicas": 1,
      "active_primary_shards": 3,
      "active_shards": 6,
      "relocating_shards": 0,
      "initializing_shards": 0,
      "unassigned_shards": 0
    },
    "logstash-2017.06.18": {
      "status": "green",
      "number_of_shards": 3,
      "number_of_replicas": 1,
      "active_primary_shards": 3,
      "active_shards": 6,
      "relocating_shards": 0,
      "initializing_shards": 0,
      "unassigned_shards": 0
    }}
 5
Author: PShetty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-16 09:44:24

Te daré la consulta que puedes ejecutar en kibana.

GET /_cat/indices?v

Y la versión CURL será

CURL -XGET http://localhost:9200/_cat/indices?v
 4
Author: Pinkesh Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-25 19:59:50

_stats/indices da el resultado con indices.

$ curl -XGET "localhost:9200/_stats/indices?pretty=true"
{
  "_shards" : {
    "total" : 10,
    "successful" : 5,
    "failed" : 0
  },
  "_all" : {
    "primaries" : { },
    "total" : { }
  },
  "indices" : {
    "visitors" : {
      "primaries" : { },
      "total" : { }
    }
  }
}
 2
Author: prayagupd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-09 08:25:17

La gente aquí ha respondido cómo hacerlo en curl y sense, algunas personas podrían necesitar hacer esto en java.

Aquí va

client.admin().indices().stats(new IndicesStatsRequest()).actionGet().getIndices().keySet()
 2
Author: Avinash Kumar Pandey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-28 08:21:20

Pruebe esta API cat: le dará la lista de todos los índices con el estado y otros detalles.

CURL-XGET http://localhost:9200/_cat/indices

 2
Author: Gaurav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-18 11:05:43

Uso el punto final _stats/indexespara obtener un blob json de datos y luego filtrar con jq.

curl 'localhost:9200/_stats/indexes' | jq '.indices | keys | .[]'

"admin"
"blazeds"
"cgi-bin"
"contacts_v1"
"flex2gateway"
"formmail"
"formmail.pl"
"gw"
...

Si no desea comillas, agregue una bandera -r a jq.

Sí, el punto final es indexes y la clave de datos es indices, por lo que tampoco pudieron decidirse:)

Necesitaba esto para limpiar estos índices de basura creados por un análisis de seguridad interna (nessus).

PS. Recomiendo encarecidamente familiarizarse con jq si va a interactuar con ES desde el línea de comandos.

 1
Author: spazm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-15 18:00:49
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>2.4.0</version>
</dependency>

API de Java

Settings settings = Settings.settingsBuilder().put("cluster.name", Consts.ES_CLUSTER_NAME).build();
TransportClient client = TransportClient.builder().settings(settings).build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("52.43.207.11"), 9300));
IndicesAdminClient indicesAdminClient = client.admin().indices();
GetIndexResponse getIndexResponse = indicesAdminClient.getIndex(new GetIndexRequest()).get();
for (String index : getIndexResponse.getIndices()) {
    logger.info("[index:" + index + "]");
}
 1
Author: StanislavKo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-10 15:14:36

Aquí hay otra forma de ver los índices en la base de datos:

curl -sG somehost-dev.example.com:9200/_status --user "credentials:password" | sed 's/,/\n/g' | grep index | grep -v "size_in" | uniq


{ "index":"tmpdb"}

{ "index":"devapp"}
 0
Author: TheodoreC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-16 11:55:45

Una de las mejores formas de listar índices + para mostrar su estado junto con list : es simplemente ejecutando la siguiente consulta.

Nota: preferiblemente use Sense para obtener la salida adecuada.

curl -XGET 'http://localhost:9200/_cat/shards'

La salida de muestra es la siguiente. La principal ventaja es que básicamente muestra el nombre del índice y los fragmentos en los que se guardó, el tamaño del índice y los fragmentos ip, etc

index1     0 p STARTED     173650  457.1mb 192.168.0.1 ip-192.168.0.1 
index1     0 r UNASSIGNED                                                 
index2     1 p STARTED     173435  456.6mb 192.168.0.1 ip-192.168.0.1 
index2     1 r UNASSIGNED                                                 
...
...
...
 0
Author: Ritesh Aryal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-01 16:33:41

Si está trabajando en scala, una forma de hacer esto y usar Future es crear un RequestExecutor, luego use el IndicesStatsRequestBuilder y el cliente administrativo para enviar su solicitud.

import org.elasticsearch.action.{ ActionRequestBuilder, ActionListener, ActionResponse }
import scala.concurrent.{ Future, Promise, blocking }

/** Convenice wrapper for creating RequestExecutors */
object RequestExecutor {
    def apply[T <: ActionResponse](): RequestExecutor[T] = {
        new RequestExecutor[T]
    }
}

/** Wrapper to convert an ActionResponse into a scala Future
 *
 *  @see http://chris-zen.github.io/software/2015/05/10/elasticsearch-with-scala-and-akka.html
 */
class RequestExecutor[T <: ActionResponse] extends ActionListener[T] {
    private val promise = Promise[T]()

    def onResponse(response: T) {
        promise.success(response)
    }

    def onFailure(e: Throwable) {
        promise.failure(e)
    }

    def execute[RB <: ActionRequestBuilder[_, T, _, _]](request: RB): Future[T] = {
        blocking {
            request.execute(this)
            promise.future
        }
    }
}

El ejecutor se levanta de esta entrada de blog que es definitivamente una buena lectura si estás tratando de consultar ES mediante programación y no a través de curl. Una vez que tenga esto, puede crear una lista de todos los índices con bastante facilidad:

def totalCountsByIndexName(): Future[List[(String, Long)]] = {
    import scala.collection.JavaConverters._
    val statsRequestBuider = new IndicesStatsRequestBuilder(client.admin().indices())
    val futureStatResponse = RequestExecutor[IndicesStatsResponse].execute(statsRequestBuider)
    futureStatResponse.map { indicesStatsResponse =>
        indicesStatsResponse.getIndices().asScala.map {
            case (k, indexStats) => {
                val indexName = indexStats.getIndex()
                val totalCount = indexStats.getTotal().getDocs().getCount()
                    (indexName, totalCount)
                }
        }.toList
    }
}

client es una instancia de Cliente que puede ser un nodo o un cliente de transporte, lo que se adapte a sus necesidades. También necesitará tener un ExecutionContext implícito en el alcance de esta solicitud. Si intenta compilar este código sin él, recibirá una advertencia del compilador de scala sobre cómo obtenerlo si no tiene uno importado ya.

Necesitaba el recuento de documentos, pero si realmente solo necesita los nombres de los índices, puede extraerlos de las teclas del mapa en lugar de IndexStats:

indicesStatsResponse.getIndices().keySet()

Esta pregunta aparece cuando estás buscando cómo hacer esto incluso si estás tratando de hacerlo programáticamente, así que espero que esto ayude a cualquiera que busque hacer esto en scala/java. De lo contrario, los usuarios de curl pueden hacer lo que dice la respuesta superior y usar

curl http://localhost:9200/_aliases
 0
Author: EdgeCaseBerg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-15 14:12:34