> ## Documentation Index
> Fetch the complete documentation index at: https://docs.oasm.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Componer consultas

> Combina lotes, filas relacionadas, listas, filtros y recuentos en Attack Surface Query para responder preguntas reales sobre la superficie de ataque

Las piezas básicas (`select`, `include`, `where`, ventanas y agregaciones) se combinan libremente. Esta página parte de preguntas que la gente hace de verdad y muestra el patrón que hay detrás de cada respuesta, y después un recetario de lotes completos que puedes pegar en la API.

## Patrón 1: agrupa las preguntas en un lote

Pon todas las partes de una pregunta en un mismo lote. Las consultas se ejecutan en paralelo, y una consulta que falla no detiene a las demás.

```json theme={null}
{
  "window": { "since": "now-7d" },
  "queries": {
    "newHosts": { "from": "hosts", "select": ["value", "kind", "target.value"] },
    "newPorts": { "from": "services", "select": ["host.value", "port", "http.title"] },
    "newFindings": { "from": "vulnerabilities", "select": ["name", "severity", "host.value"],
                     "where": { "logic": "and", "items": [{ "field": "isOpen", "op": "eq", "value": "true" }] } },
    "allTimePorts": { "from": "services", "groupBy": ["port"], "aggregate": { "n": { "fn": "count" } }, "window": null }
  }
}
```

La `window` del lote es la predeterminada; `allTimePorts` la descarta con `"window": null`.

## Patrón 2: amplía una fila con campos relacionados

Empieza por el recurso sobre el que trata la pregunta y trae el contexto con rutas con puntos. *"¿Qué certificados TLS caducan este mes, en qué host y puerto, y qué dice el sitio?"*

```json theme={null}
{ "from": "tls",
  "select": ["subjectCn", "notAfter", "daysToExpiry", "service.host.value", "service.port"],
  "where": { "logic": "and", "items": [{ "field": "notAfter", "op": "lt", "value": "now+30d" }] },
  "orderBy": [{ "field": "notAfter", "dir": "asc" }] }
```

## Patrón 3: filtra por una cosa, devuelve otra

`where` puede comprobar filas relacionadas y listas que el resultado no muestra. *"Servicios que ejecutan WordPress en un host que tiene un hallazgo crítico."*

```json theme={null}
{ "from": "services",
  "select": ["host.value", "port", "http.title"],
  "where": { "logic": "and", "items": [
    { "field": "technologies.name", "op": "eq", "value": "WordPress" },
    { "field": "host.vulnerabilities.severity", "op": "eq", "value": "critical" } ] } }
```

Una ruta de filtro puede pasar por filas relacionadas antes y después de una lista (`host.vulnerabilities.severity`, `services.http.title`), pero por **una lista como máximo**: `services.technologies.name` desde `hosts` se rechaza. Empieza en su lugar por el recurso que está una lista más cerca, como arriba.

> [!NOTE]
>
> Cada condición sobre una lista se comprueba por separado: el host tiene *algún* hallazgo crítico, no necesariamente uno abierto aunque añadas `host.vulnerabilities.isOpen` como segunda condición. Para ligar varias condiciones a la misma fila relacionada, usa una [prueba de relación](https://docs.oasm.io/es/attack-surface-query/filtering.md#relation-tests) (patrón 9) o consulta el recurso de esa fila (patrón 4).

## Patrón 4: consulta la hija, no el padre

Cuando la pregunta trata sobre las hijas, léelas directamente y trae el padre con un campo relacionado. Esta es también la salida cuando un include es demasiado grande. *"Todos los servicios que ejecutan un nginx desactualizado, con su host."*

```json theme={null}
{ "from": "technologies",
  "select": ["name", "version", "service.host.value", "service.port"],
  "where": { "logic": "and", "items": [
    { "field": "name", "op": "eq", "value": "nginx" },
    { "field": "version", "op": "in", "value": ["1.18.0", "1.20.1", "1.22.0"] } ] },
  "limit": 200 }
```

## Patrón 5: una fila con todo lo que la rodea

`include` adjunta listas a cada fila; anídalas para bajar dos niveles. Mantén pequeño el `limit` del padre. *"Todo lo que se sabe de api.example.com."*

```json theme={null}
{
  "queries": {
    "host": {
      "from": "hosts",
      "select": ["value", "kind", "firstSeen", "lastSeen", "target.value"],
      "limit": 1,
      "where": { "logic": "and", "items": [{ "field": "value", "op": "eq", "value": "api.example.com" }] },
      "include": {
        "services": {
          "select": ["port", "http.title", "http.statusCode", "http.webserver"],
          "limit": 20,
          "include": { "technologies": { "select": ["name", "version"] } }
        },
        "vulnerabilities": { "select": ["name", "severity", "detectionStatus"], "limit": 20 }
      }
    },
    "ips": {
      "from": "ips",
      "select": ["ip", "source"],
      "where": { "logic": "and", "items": [{ "field": "host.value", "op": "eq", "value": "api.example.com" }] }
    }
  }
}
```

Las IPs son una segunda consulta del mismo lote en lugar de un tercer include: una consulta tiene como máximo cinco includes en total (tres para el agente de IA), contando los anidados.

## Patrón 6: filtra las hijas incluidas

El `where` propio de un include limita qué hijas se adjuntan, sin filtrar los padres. *"Todos los hosts, solo con sus servicios que parecen de administración."*

```json theme={null}
{ "from": "hosts", "select": ["value"], "limit": 50,
  "include": { "services": {
    "select": ["port", "http.title"], "limit": 5,
    "where": { "logic": "and", "items": [{ "field": "http.title", "op": "contains", "value": "admin" }] } } } }
```

Para conservar solo los hosts que *tienen* un servicio así, añade la misma condición al `where` del padre como ruta de lista:

```json theme={null}
{ "from": "hosts", "select": ["value"], "limit": 50,
  "where": { "logic": "and", "items": [{ "field": "services.http.title", "op": "contains", "value": "admin" }] },
  "include": { "services": {
    "select": ["port", "http.title"], "limit": 5,
    "where": { "logic": "and", "items": [{ "field": "http.title", "op": "contains", "value": "admin" }] } } } }
```

## Patrón 7: lista y recuento a la vez

Una lista y su distribución son dos consultas de un mismo lote, con el mismo filtro.

```json theme={null}
{
  "queries": {
    "critical": { "from": "vulnerabilities", "select": ["name", "cvssScore", "cve", "host.value"],
      "where": { "logic": "and", "items": [
        { "field": "isOpen", "op": "eq", "value": "true" },
        { "field": "severity", "op": "eq", "value": "critical" } ] },
      "orderBy": [{ "field": "cvssScore", "dir": "desc" }], "limit": 100 },
    "criticalPerHost": { "from": "vulnerabilities", "groupBy": ["host.value"], "aggregate": { "n": { "fn": "count" } },
      "where": { "logic": "and", "items": [
        { "field": "isOpen", "op": "eq", "value": "true" },
        { "field": "severity", "op": "eq", "value": "critical" } ] } }
  }
}
```

## Patrón 8: continúa con los ids

Cada fila lleva un `id`. Úsalo en el siguiente lote para profundizar, o pásalo a otras APIs de OASM.

```json theme={null}
{ "from": "services", "select": ["port", "http.title"],
  "where": { "logic": "and", "items": [{ "field": "host.id", "op": "in", "value": ["1396ad91-…", "e4e5c8ca-…"] }] } }
```

## Patrón 9: pregunta por lo que falta

Algunas de las preguntas de seguridad más útiles tratan sobre ausencias: un host que sirve HTTP pero no HTTPS, un objetivo al que ya no le queda ningún host, un servicio que nadie ha identificado. Las pruebas de relación lo expresan directamente. *"Hosts que responden en el puerto 80 pero no tienen nada en el 443."*

```json theme={null}
{ "from": "hosts", "select": ["value", "target.value"], "limit": 100,
  "where": { "logic": "and", "items": [
    { "relation": "services", "where": { "logic": "and", "items": [{ "field": "port", "op": "eq", "value": "80" }] } },
    { "relation": "services", "quantifier": "none", "where": { "logic": "and", "items": [{ "field": "port", "op": "eq", "value": "443" }] } } ] } }
```

La misma forma cubre *todos* (`"quantifier": "every"`: todos los puertos de un host son puertos web) y *cuántos* (`"count": { "op": "gte", "value": "10" }`: hosts con diez puertos abiertos o más).

## Patrón 10: una matriz en una sola consulta

Cuando una tabla necesita una columna por categoría, da a cada agregado su propio `where` en lugar de ejecutar una consulta por categoría. Después, conserva solo las filas interesantes con `having`. *"Objetivos ordenados por hallazgos abiertos críticos y altos, solo los que tienen alguno."*

```json theme={null}
{ "from": "vulnerabilities",
  "groupBy": ["host.target.value"],
  "where": { "logic": "and", "items": [{ "field": "isOpen", "op": "eq", "value": "true" }] },
  "aggregate": {
    "critical": { "fn": "count", "where": { "logic": "and", "items": [{ "field": "severity", "op": "eq", "value": "critical" }] } },
    "high": { "fn": "count", "where": { "logic": "and", "items": [{ "field": "severity", "op": "eq", "value": "high" }] } },
    "hosts": { "fn": "countDistinct", "field": "host.id" } },
  "having": { "logic": "or", "items": [
    { "field": "critical", "op": "gt", "value": "0" },
    { "field": "high", "op": "gt", "value": "0" } ] },
  "orderBy": [{ "field": "critical", "dir": "desc" }, { "field": "high", "dir": "desc" }] }
```

## Patrón 11: un gráfico sin huecos

Una serie para un gráfico necesita un punto por día, incluidos los días sin actividad, en la zona horaria de quien lo ve. `fill` y `options.timezone` dan exactamente eso. *"Nuevos puertos y nuevos hallazgos por día en los últimos 30 días, hora de Hanói."*

```json theme={null}
{
  "window": { "since": "now-30d" },
  "options": { "timezone": "Asia/Ho_Chi_Minh" },
  "queries": {
    "ports": { "from": "services", "groupBy": [{ "field": "firstSeen", "bucket": "day" }],
               "aggregate": { "n": { "fn": "count" } }, "fill": true },
    "findings": { "from": "vulnerabilities", "groupBy": [{ "field": "firstSeen", "bucket": "day" }],
                  "aggregate": { "n": { "fn": "count" },
                                 "critical": { "fn": "count", "where": { "logic": "and", "items": [{ "field": "severity", "op": "eq", "value": "critical" }] } } },
                  "fill": true }
  }
}
```

Ambas series tienen los mismos días en el mismo orden, así que encajan en un mismo gráfico.

## Recetario

> [accordion] Objetivos y cuántos hosts tiene cada uno
>
> ```json theme={null}
> { "queries": {
>   "targets": { "from": "targets", "select": ["value", "type", "firstSeen"], "limit": 200 },
>   "hostsPerTarget": { "from": "hosts", "groupBy": ["target.value"], "aggregate": { "hosts": { "fn": "count" } },
>                       "orderBy": [{ "field": "hosts", "dir": "desc" }], "limit": 200 } } }
> ```

> [accordion] Nuevos dominios y puertos de los últimos 5 días
>
> ```json theme={null}
> { "window": { "since": "now-5d" }, "queries": {
>   "domains": { "from": "hosts", "select": ["value", "firstSeen", "target.value"],
>                "where": { "logic": "and", "items": [{ "field": "kind", "op": "eq", "value": "domain" }] } },
>   "ports": { "from": "services", "select": ["host.value", "port", "http.title", "http.statusCode"] } } }
> ```

> [accordion] Servicios de riesgo expuestos
>
> ```json theme={null}
> { "from": "services", "select": ["host.value", "port", "http.title"], "limit": 200,
>   "where": { "logic": "and", "items": [
>     { "field": "port", "op": "in", "value": ["21", "23", "445", "3306", "3389", "5432", "6379", "9200", "27017"] } ] } }
> ```

> [accordion] Páginas de inicio de sesión y de administración
>
> ```json theme={null}
> { "from": "services", "select": ["host.value", "port", "http.url", "http.title"], "limit": 100,
>   "where": { "logic": "or", "items": [
>     { "field": "http.title", "op": "contains", "value": "admin" },
>     { "field": "http.title", "op": "contains", "value": "login" },
>     { "field": "technologies.name", "op": "in", "value": ["Jenkins", "Grafana", "Kibana", "phpMyAdmin"] } ] } }
> ```

> [accordion] Hosts en un rango de red
>
> ```json theme={null}
> { "from": "ips", "select": ["ip", "host.value", "host.target.value"],
>   "where": { "logic": "and", "items": [{ "field": "ip", "op": "inSubnet", "value": ["203.0.113.0/24", "198.51.100.0/24"] }] } }
> ```

> [accordion] Versiones de tecnologías en uso
>
> ```json theme={null}
> { "from": "technologies", "groupBy": ["name", "version"], "aggregate": { "services": { "fn": "count" } },
>   "orderBy": [{ "field": "services", "dir": "desc" }], "limit": 50 }
> ```

> [accordion] Dónde está presente un CVE
>
> ```json theme={null}
> { "from": "vulnerabilities", "select": ["name", "severity", "host.value", "affectedUrl", "detectionStatus"],
>   "where": { "logic": "and", "items": [{ "field": "cve", "op": "eq", "value": "CVE-2024-3400" }] } }
> ```

> [accordion] Hosts que ningún escaneo ha visto en 30 días
>
> ```json theme={null}
> { "from": "hosts", "select": ["value", "lastSeen", "target.value"], "limit": 200,
>   "where": { "logic": "and", "items": [{ "field": "lastSeen", "op": "lt", "value": "now-30d" }] },
>   "orderBy": [{ "field": "lastSeen", "dir": "asc" }] }
> ```

> [accordion] Hallazgos por semana y severidad
>
> ```json theme={null}
> { "window": { "since": "now-90d" }, "queries": { "trend": {
>   "from": "vulnerabilities",
>   "groupBy": [{ "field": "firstSeen", "bucket": "week" }, "severity"],
>   "aggregate": { "n": { "fn": "count" } }, "limit": 100 } } }
> ```

> [accordion] Certificados que caducan en 30 días, wildcards primero
>
> ```json theme={null}
> { "from": "tls", "select": ["subjectCn", "notAfter", "wildcard", "service.host.value", "service.port"],
>   "where": { "logic": "and", "items": [{ "field": "notAfter", "op": "between", "value": ["now", "now+30d"] }] },
>   "orderBy": [{ "field": "notAfter", "dir": "asc" }] }
> ```

> [accordion] Servicios sin respuesta HTTP
>
> ```json theme={null}
> { "from": "services", "select": ["host.value", "port", "lastSeen"], "limit": 200,
>   "where": { "logic": "and", "items": [{ "field": "http.title", "op": "isNull" }, { "field": "http.statusCode", "op": "isNull" }] } }
> ```

> [accordion] Solo hosts de producción (excluye nombres de dev, staging e internos)
>
> ```json theme={null}
> { "from": "hosts", "select": ["value", "target.value"], "limit": 200,
>   "where": { "logic": "and", "items": [{ "not": { "logic": "or", "items": [
>     { "field": "value", "op": "startsWith", "value": "dev" },
>     { "field": "value", "op": "startsWith", "value": "staging" },
>     { "field": "value", "op": "endsWith", "value": ".internal" } ] } }] } }
> ```

> [accordion] Hallazgos que tienen dos CVEs a la vez
>
> ```json theme={null}
> { "from": "vulnerabilities", "select": ["name", "cve", "host.value"],
>   "where": { "logic": "and", "items": [{ "field": "cve", "op": "containsAll", "value": ["CVE-2024-3400", "CVE-2024-3401"] }] } }
> ```

> [accordion] Hosts fuera de tus rangos conocidos
>
> ```json theme={null}
> { "from": "ips", "select": ["ip", "host.value"], "limit": 200,
>   "where": { "logic": "and", "items": [{ "field": "ip", "op": "notInSubnet", "value": ["10.0.0.0/8", "172.16.0.0/12", "203.0.113.0/24"] }] } }
> ```

> [accordion] Registros DNS que apuntan a un proveedor
>
> ```json theme={null}
> { "from": "dnsRecords", "select": ["recordType", "value", "host.value"],
>   "where": { "logic": "and", "items": [
>     { "field": "recordType", "op": "eq", "value": "CNAME" },
>     { "field": "value", "op": "contains", "value": "cloudfront.net" } ] } }
> ```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.