﻿---
title: Dynamic query building
description: Most real search is not one static template. The application looks at the query and decides. A short query goes lexical, and a long one goes semantic...
url: https://docs-v3-preview.elastic.dev/workflow/dynamic-queries
---

# Dynamic query building
Most real search is not one static template. The application looks at the query and decides. A short query goes lexical, and a long one goes semantic. A filter depends on
the region, and a boost depends on the tenant. A static template cannot measure
that, and a copy of the logic in a test drifts from production.
A `builder` target runs **your query-building code**. For every query, judy starts your command, hands it the query, and reads back the request to send. The command can be a bash script, a Node or Python file, or a wrapper around the function your application already uses. judy then sends the request to Elasticsearch itself. It knows exactly what it sent, and it records the request.
```mermaid
sequenceDiagram
    participant J as judy
    participant B as Your command
    participant E as Elasticsearch
    J->>B: the query
    B-->>J: the request
    J->>E: search
    E-->>J: ranked results
    Note over J: score the results
```

```yaml
targets:
  router: {builder: {cluster: live, index: wands, command: [./router.sh]}, params: {min_words: 3}}
```

That is all a builder is. You try an idea fast: edit a script, run `judy run` or `judy compare`, and read the result.
An agent can experiment with a builder as easily as you can. It can iterate on a query builder in a few lines of bash and
measure each version. It writes the real one last.

## What your command receives

The command is started **once per query**, in the folder of the configuration file (or the target's `cwd`), so `./router.sh`
works from anywhere. It gets the request in two forms, so use whichever is easier:

|                     | Content                                                                                                                                      |
|---------------------|----------------------------------------------------------------------------------------------------------------------------------------------|
| standard input      | one JSON line, then end of input: `{"v":1,"id":1,"query":"salon chair","size":10,"queryId":"0","params":{"min_words":3}}`                    |
| `JUDY_QUERY`        | the query text                                                                                                                               |
| `JUDY_SIZE`         | how many results judy wants                                                                                                                  |
| `JUDY_QUERY_ID`     | the query's id in the judgement set                                                                                                          |
| `JUDY_PARAM_<NAME>` | each of the target's [tuning parameters](/concepts/targets#tuning-parameters), the name in upper case: `min_words` is `JUDY_PARAM_MIN_WORDS` |

A script that answers from the environment need not read standard input at all.

## What it prints

The first line of standard output, a JSON object with one of:

| Answer                                        | Meaning                                                 |
|-----------------------------------------------|---------------------------------------------------------|
| `{"dsl":{…}}`                                 | a Query DSL body, sent to `{index}/_search`             |
| `{"esql":"FROM …","params":[{"name":value}]}` | an ES|QL query with named parameters                    |
| `{"error":"why"}`                             | the builder cannot build this query; the run reports it |

And, optionally, next to `dsl` or `esql`:

| Field     | Meaning                                                                                                       |
|-----------|---------------------------------------------------------------------------------------------------------------|
| `"index"` | the index for this query, overriding the target's `index` (required if the target sets none)                  |
| `"mode"`  | `"lexical"`, `"semantic"` or `"hybrid"`: what this request is. It wins over what judy infers from the request |

Everything after the first line is ignored. Three cases are errors: a line that is not JSON, a command that exits without printing, and no answer within
`timeout_seconds` (60 by default). The error names the problem and includes the end of the command's standard error.
Keep standard output for the answer and write logs to standard error.

## A builder in a dozen lines

This builder is a router: queries of `min_words` words or more go semantic, the rest lexical, and it states its mode. It needs
`jq` to write JSON safely; any language works the same way.
```sh
#!/bin/bash
# Semantic from min_words words, lexical below that. judy starts this once per query and sets
# JUDY_QUERY and JUDY_SIZE, and JUDY_PARAM_MIN_WORDS from the target's params.
SRC='["product_id","product_name","product_class","product_description"]'
words=$(wc -w <<< "$JUDY_QUERY")
if [ "$words" -ge "${JUDY_PARAM_MIN_WORDS:-3}" ]; then
  jq -nc --arg q "$JUDY_QUERY" --argjson size "$JUDY_SIZE" --argjson src "$SRC" \
    '{mode: "semantic", dsl: {size: $size, _source: $src, query: {semantic: {field: "product_semantic", query: $q}}}}'
else
  jq -nc --arg q "$JUDY_QUERY" --argjson size "$JUDY_SIZE" --argjson src "$SRC" \
    '{mode: "lexical", dsl: {size: $size, _source: $src, query: {multi_match: {query: $q,
      fields: ["product_name^3","product_class^2","category_hierarchy","product_description","product_features"]}}}}'
fi
```

Run by hand to see what it builds for a short and a long query (real output, with the field lists abbreviated):
```text
$ JUDY_QUERY="salon chair" JUDY_SIZE=10 ./router.sh
{"mode":"lexical","dsl":{"size":10,"_source":[…],"query":{"multi_match":{"query":"salon chair","fields":["product_name^3", …]}}}}
$ JUDY_QUERY="low profile loveseat recliner" JUDY_SIZE=10 ./router.sh
{"mode":"semantic","dsl":{"size":10,"_source":[…],"query":{"semantic":{"field":"product_semantic","query":"low profile loveseat recliner"}}}}
```


## Tuning a builder without editing it

Parameters make the logic itself something you can sweep. `--target router:min_words=2` runs the same builder with another value:
```sh
judy compare router router:min_words=2 --set wands.judgements.yaml
```

Real output on the WANDS set, 480 queries (the "in plain words" block is added after the numbers):
```text
ran 480 queries against router in 15.5s
ran 480 queries against router:min_words=2 in 16.7s
ndcg@10: router -> router:min_words=2 over 479 paired queries
  mean 0.631 -> 0.645  (+0.014)
  49 better, 394 same, 36 worse   p = 0.0688 (not distinguishable from noise)
  108 queries were sent a different search request
  1 queries could not be paired

most improved
   +1.000  0.000 -> 1.000  oriental vanity
   +0.760  0.066 -> 0.826  togo chair
   +0.740  0.000 -> 0.740  nautical platters
   +0.719  0.281 -> 1.000  beaded curtains
   +0.716  0.284 -> 1.000  china clock

most regressed
   -0.875  0.958 -> 0.083  malachi sled
   -0.797  1.000 -> 0.203  delta trinsic
   -0.752  0.812 -> 0.060  zachary 72.5
   -0.722  0.932 -> 0.209  verden callan
   -0.622  0.841 -> 0.219  mystic swivel

in plain words
  No reliable difference: ndcg@10 moved by +0.014 on average (2% more than the baseline's 0.631),
    but that is within what chance produces on these queries (p = 0.0688). Treat the two as equal
    unless you have another reason.
  49 of 479 queries improved (10%), 36 got worse (8%) and 394 did not change.
```

The two settings are not distinguishable here (p = 0.07): 49 queries improved and 36 got worse, which is what noise looks like.

## Wrapping your real query builder

The point of a builder is that it is the code your application runs. Whatever language you build queries in, a thin wrapper that
reads the request, calls your query-building function and prints the request is enough. In pseudo-code:
```text
request = parse(stdin)                      
body    = build_search_request(request.query, request.params)  
print(json({dsl: body}))
```

- **Do not search.** Return the request. judy sends it, so it can record exactly what was sent and talks to the cluster the
  same way as for every other target.
- **Report what you cannot build** with `{"error":"why"}` instead of exiting silently.


## When starting the command is too slow: `lifetime: process`

Starting a process per query is fine for a script. Suppose your builder takes seconds to start, or holds state worth keeping, such as a loaded model or a cache. Ask for one
long-lived process:
```yaml
targets:
  app: {builder: {cluster: live, index: wands, command: [node, build-query.js], lifetime: process}}
```

judy then starts the command once and speaks in lines. It writes one request line per query to standard input, and reads one
answer line from standard output for each. The request line is the same JSON as above, and **the answer must echo the `id`** so
judy can match the two:
```text
{"v":1,"id":1,"query":"salon chair","size":10,"queryId":"0","params":{}}
{"id":1,"dsl":{…}}
```

Write each answer as a single line and flush standard output. The `JUDY_*` environment variables are not set in this mode, since
the process outlives the query: read the request line instead. judy sends a long-lived builder one query at a time.

## What you get

A builder target is an ordinary target. `judy run`, `judy compare`, `judy modes` and gates all work on it. The file
`{set}.{target}.requests.jsonl` holds the request that your code built for every query:
```text
{"id":"0","hash":"0d6519b2be78","request":{"size":10,"_source":[…],"query":{"multi_match":{…}}}}
```

Because a builder can state its mode, `mode:semantic` and `mode:lexical` groups appear in the scorecard even when the request
alone would not say. See [modes](https://docs-v3-preview.elastic.dev/concepts/modes) for what to do with them.