Consulta de Elasticsearch para devolver todos los registros


Tengo una pequeña base de datos en Elasticsearch y para fines de prueba me gustaría recuperar todos los registros. Estoy intentando usar una URL del formulario...

http://localhost:9200/foo/_search?pretty=true&q={'matchAll':{''}}

¿Puede alguien darme la URL que usaría para lograr esto, por favor?

Author: Aminah Nuraini, 2012-01-12

22 answers

Creo que la sintaxis de lucene es soportada así que:

http://localhost:9200/foo/_search?pretty=true&q=*:*

El tamaño predeterminado es 10, por lo que también puede necesitar &size=BIGNUMBER para obtener más de 10 elementos. (donde BIGNUMBER es igual a un número que cree que es más grande que su conjunto de datos)

PERO, la documentación de elasticsearch sugiere para conjuntos de resultados grandes, utilizando el tipo de búsqueda scan.

EG:

curl -XGET 'localhost:9200/foo/_search?search_type=scan&scroll=10m&size=50' -d '
{
    "query" : {
        "match_all" : {}
    }
}'

Y luego seguir solicitando según el enlace de documentación anterior sugiere.

EDITAR: scan Obsoleto en 2.1.0.

scan no proporciona ningún beneficio sobre una solicitud regular scroll ordenada por _doc. enlace a elastic docs (descubierto por @christophe-roussy)

 561
Author: Steve Casey,
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-25 04:10:09
http://127.0.0.1:9200/foo/_search/?size=1000&pretty=1
                                   ^

Tenga en cuenta el tamaño param, que aumenta las visitas mostradas desde el valor predeterminado (10) a 1000 por fragmento.

Http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-from-size.html

 103
Author: lfender6445,
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-07-19 14:33:10

Elasticsearch(ES) admite una solicitud GET o POST para obtener los datos del índice del clúster ES.

Cuando hacemos un GET:

http://localhost:9200/[your index name]/_search?size=[no of records you want]&q=*:*

Cuando hacemos un POST:

http://localhost:9200/[your_index_name]/_search
{
  "size": [your value] //default 10
  "from": [your start index] //default 0
  "query":
   {
    "match_all": {}
   }
}   

Sugeriría usar un plugin de interfaz de usuario con elasticsearch http://mobz.github.io/elasticsearch-head / Esto le ayudará a obtener una mejor sensación de los índices que crea y también probar sus índices.

 24
Author: Prerak Diwan,
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-09-28 21:31:46

La consulta a continuación devolverá los NO_OF_RESULTS que desea que se devuelvan..

curl -XGET 'localhost:9200/foo/_search?size=NO_OF_RESULTS' -d '
{
"query" : {
    "match_all" : {}
  }
}'

Ahora, la pregunta aquí es que desea que se devuelvan todos los registros. Así que naturalmente, antes de escribir una consulta, no sabrás el valor de NO_OF_RESULTS.

¿Cómo sabemos cuántos registros existen en su documento? Simplemente escriba la consulta a continuación

curl -XGET 'localhost:9200/foo/_search' -d '

Esto te daría un resultado que se parece al siguiente

 {
hits" : {
  "total" :       2357,
  "hits" : [
    {
      ..................

El resultado total le indica cuántos registros hay disponibles en su documento. Por lo tanto, esa es una buena manera de saber el valor de NO_OF RESULTADOS

curl -XGET 'localhost:9200/_search' -d ' 

Buscar todos los tipos en todos los índices

curl -XGET 'localhost:9200/foo/_search' -d '

Buscar todos los tipos en el índice foo

curl -XGET 'localhost:9200/foo1,foo2/_search' -d '

Buscar todos los tipos en los índices foo1 y foo2

curl -XGET 'localhost:9200/f*/_search

Buscar todos los tipos en cualquier índice que comience con f

curl -XGET 'localhost:9200/_all/type1,type2/_search' -d '

Tipos de búsqueda usuario y tweet en todos los índices

 16
Author: vjpan8564,
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-11 02:36:01

Esta es la mejor solución que encontré usando python client

  # Initialize the scroll
  page = es.search(
  index = 'yourIndex',
  doc_type = 'yourType',
  scroll = '2m',
  search_type = 'scan',
  size = 1000,
  body = {
    # Your query's body
    })
  sid = page['_scroll_id']
  scroll_size = page['hits']['total']

  # Start scrolling
  while (scroll_size > 0):
    print "Scrolling..."
    page = es.scroll(scroll_id = sid, scroll = '2m')
    # Update the scroll ID
    sid = page['_scroll_id']
    # Get the number of results that we returned in the last scroll
    scroll_size = len(page['hits']['hits'])
    print "scroll size: " + str(scroll_size)
    # Do something with the obtained page

Https://gist.github.com/drorata/146ce50807d16fd4a6aa

Usando el cliente java

import static org.elasticsearch.index.query.QueryBuilders.*;

QueryBuilder qb = termQuery("multi", "test");

SearchResponse scrollResp = client.prepareSearch(test)
        .addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC)
        .setScroll(new TimeValue(60000))
        .setQuery(qb)
        .setSize(100).execute().actionGet(); //100 hits per shard will be returned for each scroll
//Scroll until no hits are returned
do {
    for (SearchHit hit : scrollResp.getHits().getHits()) {
        //Handle the hit...
    }

    scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
} while(scrollResp.getHits().getHits().length != 0); // Zero hits mark the end of the scroll and the while loop.

Https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-search-scrolling.html

 15
Author: Akira Sendoh,
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-10-31 10:57:51

Use server:9200/_stats también para obtener estadísticas sobre todos sus alias.. al igual que el tamaño y el número de elementos por alias, eso es muy útil y proporciona información útil

 10
Author: TheEnglishMe,
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-18 13:21:16

Simple! Puede utilizar size y from parámetro!

http://localhost:9200/[your index name]/_search?size=1000&from=0

Luego cambia el from gradualmente hasta obtener todos los datos.

 7
Author: Aminah Nuraini,
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-04-23 22:46:17

Elasticsearch obtendrá significativo más lento si solo agrega un número grande como tamaño, un método para usar para obtener todos los documentos es usar scan y scroll ids.

Así que su llamada sería:

GET /foo/_search?search_type=scan&scroll=1m
{
    "query": { "match_all": {}},
    "size":  1000
}

Esto devolverá un _scroll_id, que ahora puede usar para obtener el primer lote de documentos.

Https://www.elastic.co/guide/en/elasticsearch/guide/current/scan-scroll.html

 5
Author: WoodyDRN,
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-11-20 15:53:06

La mejor manera de ajustar el tamaño es usando size = number delante de la URL

Curl -XGET "http://localhost:9200/logstash-*/_search?size=50&pretty"

Nota: el valor máximo que se puede definir en este tamaño es 10000. Para cualquier valor por encima de diez mil se espera que utilice la función de desplazamiento que minimizaría cualquier posibilidad de impactos en el rendimiento.

 5
Author: akshay misra,
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-08-10 14:58:23

Http://localhost:9200/foo/_search / ?size = 1000 & pretty = 1

Deberá especificar el parámetro de consulta de tamaño, ya que el valor predeterminado es 10

 5
Author: Edwin Ikechukwu,
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-04-21 10:03:22

Puede utilizar el _count API para obtener el valor del parámetro size:

http://localhost:9200/foo/_count?q=<your query>

Devuelve {count:X, ...}. Extraiga el valor ' X ' y luego haga la consulta real:

http://localhost:9200/foo/_search?q=<your query>&size=X
 5
Author: Daniel,
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-06-16 21:43:07

Algunos de ellos dieron la respuesta correcta de usar scan y scroll, aparentemente, no pude una respuesta completa que funcionara mágicamente. Cuando alguien quiere tirar de registros, entonces uno tiene que ejecutar siguiendo el comando curl.

curl -XGET 'http://ip1:9200/myindex/_search?scroll=1m' -d '
{
    "query": {
            "match_all" : {}
    }
}
'

Pero no hemos terminado aquí. La salida del comando curl anterior sería algo como esto

{"_scroll_id":"c2Nhbjs1OzUyNjE6NU4tU3BrWi1UWkNIWVNBZW43bXV3Zzs1Mzc3OkhUQ0g3VGllU2FhemJVNlM5d2t0alE7NTI2Mjo1Ti1TcGtaLVRaQ0hZU0FlbjdtdXdnOzUzNzg6SFRDSDdUaWVTYWF6YlU2Uzl3a3RqUTs1MjYzOjVOLVNwa1otVFpDSFlTQWVuN211d2c7MTt0b3RhbF9oaXRzOjIyNjAxMzU3Ow==","took":109,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":22601357,"max_score":0.0,"hits":[]}}

Es importante tener a mano _scroll_id ya que la próxima vez que ejecute el siguiente comando

    curl -XGET  'localhost:9200/_search/scroll'  -d'
    {
        "scroll" : "1m", 
        "scroll_id" : "c2Nhbjs2OzM0NDg1ODpzRlBLc0FXNlNyNm5JWUc1" 
    }
    '

Sin embargo, no creo que sea fácil de ejecutar esto manualmente. Su mejor apuesta es escribir un código java para hacer lo mismo.

    private TransportClient client = null;
    private Settings settings = ImmutableSettings.settingsBuilder()
                  .put(CLUSTER_NAME,"cluster-test").build();
    private SearchResponse scrollResp  = null;

    this.client = new TransportClient(settings);
    this.client.addTransportAddress(new InetSocketTransportAddress("ip", port));

    QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
    scrollResp = client.prepareSearch(index).setSearchType(SearchType.SCAN)
                 .setScroll(new TimeValue(60000))                            
                 .setQuery(queryBuilder)
                 .setSize(100).execute().actionGet();

    scrollResp = client.prepareSearchScroll(scrollResp.getScrollId())
                .setScroll(new TimeValue(timeVal))
                .execute()
                .actionGet();

Ahora el BUCLE en el último comando usa SearchResponse para extraer los datos.

 3
Author: Somum,
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-02-11 07:13:24

Para Elasticsearch 6.x

Solicitud: GET /foo/_search?pretty=true

Respuesta: En Hits-> total, dar el recuento de los documentos

    {
      "took": 1,
      "timed_out": false,
      "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
      },
      "hits": {
        "total": 1001,
        "max_score": 1,
        "hits": [
          {
 3
Author: Anurag,
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-05-09 13:40:50

Size param aumenta las visitas mostradas desde el valor predeterminado(10) a 500.

http://localhost:9200/[indexName]/_search?pretty=true&size=500&q=*:*

Cambie el de paso a paso para obtener todos los datos.

http://localhost:9200/[indexName]/_search?size=500&from=0
 2
Author: Prasanna Jathan,
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-25 08:12:01

De forma predeterminada Elasticsearch devuelve 10 registros, por lo que el tamaño debe proporcionarse explícitamente.

Agregue el tamaño con la solicitud para obtener el número deseado de registros.

Http: / / {host}: 9200 / {index_name} / _search?pretty = true & size = (número de registros)

Nota : El tamaño máximo de página no puede ser superior al índice.configuración de índice max_result_window que por defecto es 10,000.

 1
Author: Satyendra 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
2018-09-28 23:59:17

Para devolver todos los registros de todos los índices puede hacer:

curl -XGET http://35.195.120.21:9200/_all/_search?size=50&pretty

Salida:

  "took" : 866,
  "timed_out" : false,
  "_shards" : {
    "total" : 25,
    "successful" : 25,
    "failed" : 0
  },
  "hits" : {
    "total" : 512034694,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "grafana-dash",
      "_type" : "dashboard",
      "_id" : "test",
      "_score" : 1.0,
       ...
 0
Author: exceltior,
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-02-14 17:39:17
curl -XGET '{{IP/localhost}}:9200/{{Index name}}/{{type}}/_search?scroll=10m&pretty' -d '{
"query": {
"filtered": {
"query": {
"match_all": {}
}}'
 0
Author: aditya,
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-03-27 18:39:32
curl -X GET 'localhost:9200/foo/_search?q=*&pretty' 
 0
Author: Dhruv 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
2018-05-22 09:53:01

El resultado máximo que devolverá elasticSearch es 10000 proporcionando el tamaño

curl -XGET 'localhost:9200/index/type/_search?scroll=1m' -d '
{
   "size":10000,
   "query" : {
   "match_all" : {}
    }
}'

Después de eso, tienes que usar Scroll API para obtener el resultado y obtener el valor _scroll_id y poner este valor en scroll_id

curl -XGET  'localhost:9200/_search/scroll'  -d'
{
   "scroll" : "1m", 
   "scroll_id" : "" 
}'
 0
Author: RAHUL JAIN,
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-07-24 10:59:09

Ninguno excepto @Akira Sendoh ha respondido cómo obtener realmente TODOS los documentos. Pero incluso esa solución bloquea mi servicio ES 6.3 sin registros. Lo único que funcionó para mí usando la biblioteca de bajo nivel elasticsearch-py fue a través de scan helper que usa scroll() api:

from elasticsearch.helpers import scan

doc_generator = scan(
    es_obj,
    query={"query": {"match_all": {}}},
    index="my-index",
)

# use the generator to iterate, dont try to make a list or you will get out of RAM
for doc in doc_generator:
    # use it somehow

Sin embargo, la forma más limpia hoy en día parece ser a través de la biblioteca elasticsearch-dsl, que ofrece llamadas más abstractas y más limpias, por ejemplo: http://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html#hits

 0
Author: chefarov,
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-08-08 21:29:03

Si todavía alguien está buscando todos los datos que se recuperarán de Elasticsearch como yo para algunos casos de uso, esto es lo que hice. Además, todos los medios de datos, todos los índices y todos los tipos de documentos. Estoy usando Elasticsearch 6.3

curl -X GET "localhost:9200/_search?pretty=true" -H 'Content-Type: application/json' -d'
{
    "query": {
        "match_all": {}
    }
}
'

Referencia de Elasticsearch

 0
Author: Santosh Kumar A,
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-08-10 06:51:26

Puede usar size = 0 esto le devolverá todos los documentos ejemplo

curl -XGET 'localhost:9200/index/type/_search' -d '
{
   size:0,
   "query" : {
   "match_all" : {}
    }
}'
 -4
Author: premkumar,
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-01-03 11:16:54