0Pricing
Elasticsearch & Full Text Search Systems · Lección

Combinación de consultas con bool

Explore la consulta `bool` para combinar varias consultas mediante las cláusulas `must`, `should`, `must_not` y `filter` y crear lógica compleja.

Combinación de consultas con bool es una lección gratuita de Elasticsearch & Full Text Search Systems en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Elasticsearch & Full Text Search Systems, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Elasticsearch & Full Text Search Systems incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Combine Search Logic

Welcome to combining queries! Up until now, we've looked at single search conditions. But real-world searches often need multiple criteria.

Elasticsearch's bool query is your go-to for building complex search logic. It lets you combine several queries using AND, OR, and NOT conditions.

Anatomy of a Bool Query

A bool query acts like a container for other queries. It has four main clauses:

  • must: All queries inside must match (AND).
  • should: At least one query inside should match (OR).
  • must_not: Queries inside must NOT match (NOT).
  • filter: Queries inside must match, but don't affect relevancy score.

We'll explore each one!

`must`: All Conditions Must Match

The must clause is like an "AND" operator. All queries listed within must must be true for a document to be considered a match.

Documents that satisfy all must clauses contribute positively to the relevancy score.

Example: `must` Clause

This query finds products that are both "laptop" AND "gaming".

{
  "query": {
    "bool": {
      "must": [
        { "match": { "category": "laptop" } },
        { "match": { "tags": "gaming" } }
      ]
    }
  }
}

`should`: At Least One Condition

The should clause is like an "OR" operator. If a document matches any of the queries listed in should, it's considered a potential match.

The more should queries a document matches, the higher its relevancy score usually is.

By default, if there are no must clauses, at least one should clause must match for a document to be returned.

Example: `should` Clause

This query finds products that are either "laptop" OR "tablet".

{
  "query": {
    "bool": {
      "should": [
        { "match": { "category": "laptop" } },
        { "match": { "category": "tablet" } }
      ]
    }
  }
}

`must_not`: Exclude Documents

The must_not clause is like a "NOT" operator. Documents matching any query inside must_not will be excluded from the results.

Queries in must_not do not contribute to the relevancy score.

Example: `must_not` Clause

This query finds all products EXCEPT those in the "refurbished" category.

{
  "query": {
    "bool": {
      "must_not": [
        { "match": { "category": "refurbished" } }
      ]
    }
  }
}

`filter`: Fast, Non-Scoring AND

The filter clause is similar to must in that all queries within it must match. However, there's a key difference:

  • No Scoring: Filter queries don't affect the relevancy score of documents.
  • Caching: Filter queries are often cached, making them very fast for frequently used criteria.

Use filter for "yes/no" conditions where you just want to include or exclude documents without influencing their rank.

Advanced: Multiple Clauses

You can combine all these clauses within a single bool query to build powerful, precise searches. This example finds:

  • Products with "laptop" in the name (must)
  • THAT are either "gaming" OR "ultrabook" (should)
  • BUT are NOT "refurbished" (must_not)
  • AND have a status of "available" (filter)
{
  "query": {
    "bool": {
      "must": { "match": { "name": "laptop" } },
      "should": [
        { "match": { "tags": "gaming" } },
        { "match": { "tags": "ultrabook" } }
      ],
      "must_not": { "term": { "condition": "refurbished" } },
      "filter": { "term": { "status.keyword": "available" } }
    }
  }
}

Complex Query Logic

Consider a bool query designed to find articles:

  • About "Elasticsearch" (must)
  • Published in "2023" OR "2024" (should)
  • But NOT written by "John Doe" (must_not)

Which of the following statements is TRUE regarding this query's behavior?

Recap: Bool Query Power

Great job! You've learned how to combine simple queries into powerful, complex search logic using Elasticsearch's bool query.

  • must: All conditions must be met (AND).
  • should: At least one condition should be met (OR).
  • must_not: Documents must NOT match these conditions (NOT).
  • filter: Conditions must be met, but don't affect relevancy (fast & cached).

Understanding bool queries is crucial for building precise and effective search applications!

Preguntas frecuentes

¿La lección «Combinación de consultas con bool» es gratis?

Sí — el texto completo de «Combinación de consultas con bool» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Elasticsearch & Full Text Search Systems, actualiza a CoddyKit PRO. El curso de Elasticsearch & Full Text Search Systems incluye 4 lecciones en total.

¿Qué aprenderé en «Combinación de consultas con bool»?

Explore la consulta `bool` para combinar varias consultas mediante las cláusulas `must`, `should`, `must_not` y `filter` y crear lógica compleja. Practicas Elasticsearch & Full Text Search Systems con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Elasticsearch & Full Text Search Systems?

No se requiere experiencia previa. Elasticsearch & Full Text Search Systems en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.

¿Cuánto tiempo toma la lección «Combinación de consultas con bool»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Elasticsearch & Full Text Search Systems?

Sí. Cada lección de Elasticsearch & Full Text Search Systems incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Introducción a Query DSL
  2. Consultas term y match
  3. Combinación de consultas con bool
  4. Filtros, rangos y contexto de consulta
← Volver a Elasticsearch & Full Text Search Systems