You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
0 Hrs
22 Min
46 Seg

Consultas de rango y agregaciones

14/16
Resources

What are range queries and how are they used in Elastic Search?

The power of Elastic Search lies in its ability to perform advanced searches through the use of range queries and aggregations. These tools allow users to perform precise searches based on specific criteria, such as numerical values or dates.

How to customize the response fields?

When a search is performed in Elastic Search, by default all the fields in the document are returned. However, it is possible to customize the search to return only the necessary information. This is done by using the "_source" option, which allows you to specify a list of fields that we want in the response.

{ " _source": ["name", "rating"], " query": { " range": { " rating": { " gt": { " gt": 3.5, " lte": 4.5 } } } } }}

In this example, the query is configured to return only the name and rating of restaurants that meet the rating range.

How to perform range queries?

Range queries are especially useful for filtering documents with values within a certain range. Whether numbers or dates, Elastic Search allows you to define these queries easily.

  • For numbers:

    When filtering by rating, the symbol GT is used to indicate "greater than", while LTE includes values "less than or equal to".

    "range": { " rating": { " gt": 3.5, " lte": 4.5 }}
  • For dates:

    When searching by last modified date, you can define the period using specific date formats.

    "range": { " last_modified.date": { " gte": "2020-01-15", " lt": "2020-03-01" } }}

In these cases, the query returns documents associated with dates between January 15 and the last day of February 2020.

What are aggregations in Elastic Search?

Aggregations are powerful tools in Elastic Search that allow you to compute metrics on the data obtained in a query.

Examples of aggregations

Aggregations allow you to perform calculations such as average, maximum and minimum on search results.

{ "aggs": { "average_rating": { "avg": { "field": { "field": "rating" } } }, "max_rating": { "max": { "field": { "field": "rating" } } }, "min_rating": { "min": { "field": { "field": "rating" }} } } }

With the results, you can identify that the average, maximum and minimum rating are computed based on the returned data.

Including missing fields in aggregations

Sometimes, documents may be missing certain fields, and it is possible to define a default value for them in aggregations. This is done using the missing property.

{ "aggs": { "average_rating": { "avg": { "field": "rating", "missing": 3.0 } } } } }} } }

Using the missing option allows you to give a default value (in this case, 3.0) to documents that have no rating, thus affecting the calculation of the overall average.

With these tools, Elastic Search enables developers to create data filtering and aggregations in a simple and efficient way, enhancing the analysis and use of stored data. Keep learning and opening new possibilities with Elastic Search!

Contributions 8

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

  • Con "_source": indicamos los campos a mostrar.
  • Agrupa las consultas que de tipo range, que están contenidas en un valor inicio (gte, gt) y fin (lte, lt)
  • Las agregaciones son métricas que se devuelven sobre una consulta.
GET /indice/_search
{
    "aggs" : {
        "campoPromedio": { 
						"avg" : { 
							"field" : "campo", 
							"missing": 3.0
							} 
				},
        "campoMaxima": { "max" : { "field" : "campo" } },
        "campoMinima": { "min" : { "field" : "campo" } }
    }
}
  • aggs, indicar consulta de agregaciones.
  • avg, valor promedio; max, valor máximo; min, valor mínimo
  • missing, establece valor por defecto a campos que que no tienen valor.

Consultas de rango
Devuelve documentos que contienen términos dentro de un rango proporcionado.

Range Queries - Elastic Search Documentation

Agregaciones
Una agregación es un indicador que permite interpretar nuestros datos y nos permiten responder preguntas del caso de negocio como por ejemplo:

¿Cuál es la puntuación promedio de los restaurantes entre el 2019 y el 2020?
¿Cuál es la categoría de restaurante mayoritaria?
¿Cual es el número de platos ofrecidos en promedio de los restaurantes?

Elasticsearch organiza las agregaciones en tres categorías:

  • “Metrics” que calculan métricas, como una suma o un promedio, a partir de valores de campo.
  • “Buckets” que agrupan documentos en cubos, también llamados bins, en función de valores de campo, rangos u otros criterios.
  • Pipelines" que toman entradas de otras agregaciones en lugar de documentos o campos.

Aggregations - Elastic Search Documentation

Por si no quieres ver los tipos con sus documentos en el salida del query dentro de un body JSON puedes insertar la keyword

// el size igual a cero nos quitara los documentos en la salida y solo nos mostrara el resultado del calculos que hagamos sobre ellos
"size": 0
"aggs": {...}

Buen dia, agradezco por favor alguien que me puedo orientar con lo siguiente:
Estoy usando kibana_sample_data_ecommerce , cuyos documentos tienen un mapeo como este.

Y quiero obtener un comportamiento diario básico de los datos de esta manera:

Hasta donde sé, tengo que dividir mis datos dos veces, primero diariamente y luego en el intervalo que deseo (1h en este caso). Después de eso, tengo que sumar las ocurrencias en ese rango de tiempo (el pequeño) y hacer una suma acumulativa durante todo el día para cada día. Para obtener algo como esto:

Esta es la consulta que estoy realizando con rangos y agregaciones:

Después de hacer eso, solo tengo que obtener "“extended stats” (estadísticas extendidas) iterando la lista de horas para todos los días, es decir:
.
Pero este último paso me está volviendo loco porque este proceso me da un nested buckets (cubos anidados), para cada intervalo de tiempo …** Entonces, la cuestión es cómo puedo hacer una agregación de estadísticas extendida sobre los datos del mes, pero solo en cada ventana de tiempo todos los días ?** Muchas gracias

Comparto mi query haciendo un AND de los ranges que quiero buscar usando los campos de calificacion y de fecha:

QUERY :

{
    // con la keyword _source le idremos excatly que campos queremos buscar dentro de nuestro query de respuesta
    "_source": ["nombre", "calificacion", "ultima_modificacion_plato1.fecha1"],
    // hacemos el query con el rango fijo de las calificaciones de un restaurante
    "query": {
        "bool":{
            "must": [
                {
                    "range": {
                        "calificacion": {"gt": 2.0, "lte": 6.0}
                    }
                },
                {
                    "range": {
                        "ultima_modificacion_plato1.fecha1": {"gt": "2018-01-01", "lte": "2020-12-31"}
                    }
                }
            ]
        }
    }
}
{
    "aggs": {
        "CalificacionPromedio": { "avg": {"field": "calificacion", "missing": 3.0} },
        "CalificacionMaxima": { "max": {"field": "calificacion"} },
        "CalificacionMinima": { "min": {"field": "calificacion"} }
    }
}
{
    "_source": ["nombre", "calification"],
    "query": {
        "range": {
            "calification": {
                "gt": 1.0,
                "lte": 5.0
            }
        }
    }
}

La sintaxis de las agregaciones es muy parecido a la sintaxis de mongodb.