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

# Query Fields Stage

export const schema = {
  "type": "object",
  "title": "Query Fields",
  "description": "Configures core Solr query parameters including query fields, return fields, sort order, and pagination settings.",
  "properties": {
    "skip": {
      "type": "boolean",
      "title": "Skip This Stage",
      "description": "Controls whether this stage executes during pipeline processing at runtime. When set to `true`, the stage is completely bypassed and documents pass through unchanged to the next stage. Useful for A/B testing, gradual rollouts, or temporarily disabling a stage without removing it from the pipeline.",
      "default": false,
      "hints": ["advanced"]
    },
    "label": {
      "type": "string",
      "title": "Label",
      "description": "Human-readable identifier displayed in the Fusion Admin UI, monitoring dashboards, and log messages. Use descriptive labels like `Parse Product PDFs` to aid debugging and team collaboration. Labels appear in performance metrics and error reports, making it easier to identify which stage failed.",
      "hints": ["advanced"],
      "maxLength": 255
    },
    "condition": {
      "type": "string",
      "title": "Condition",
      "description": "JavaScript expression evaluated at runtime on each document to conditionally execute this stage. The expression must return `true` to execute or `false` to skip. Access document fields using `doc.getFieldValue('fieldName')` and request parameters via `request.getFirstParam('paramName')`. For example, `doc.getFieldValue('type') === 'premium'` executes this stage only for premium content.",
      "hints": ["code", "code/javascript", "advanced"]
    },
    "legacy": {
      "type": "boolean",
      "title": "Legacy",
      "description": "When `true`, this stage operates in legacy mode only.",
      "hints": ["readonly", "hidden"]
    },
    "rows": {
      "type": "integer",
      "title": "Number of Results",
      "default": 10
    },
    "start": {
      "type": "integer",
      "title": "Result Offset",
      "default": 0
    },
    "sort": {
      "type": "string",
      "title": "Sort Order (Deprecated)"
    },
    "sortOrder": {
      "type": "array",
      "title": "Results Sort Order",
      "items": {
        "type": "object",
        "required": ["type"],
        "properties": {
          "type": {
            "type": "string",
            "title": "Sort Type",
            "enum": ["field", "expression", "relevancy"],
            "default": "field"
          },
          "value": {
            "type": "string",
            "title": "Field Name or Expression"
          },
          "order": {
            "type": "string",
            "title": "Sort Order",
            "enum": ["asc", "desc"]
          }
        }
      }
    },
    "queryFields": {
      "type": "array",
      "title": "Search Fields",
      "items": {
        "type": "object",
        "properties": {
          "field": {
            "type": "string",
            "title": "Field Name",
            "description": "Specifies the field name(s) for field name operations in the document processing pipeline."
          },
          "boost": {
            "type": "number",
            "title": "Field Boost"
          }
        }
      },
      "description": "Specifies the Solr fields searched when matching the query. Order may affect field prioritization in edismax queries."
    },
    "returnFields": {
      "type": "array",
      "title": "Return Fields",
      "items": {
        "type": "string"
      },
      "description": "Specifies the fields returned in each result document. Use `*` to return all fields, or list specific field names to reduce response size."
    },
    "returnScore": {
      "type": "boolean",
      "title": "Return Score",
      "default": true
    },
    "minimumMatch": {
      "type": "string",
      "title": "Minimum Should Match",
      "description": "Sets the minimum-should-match threshold for the query, controlling how many query terms must match for a document to qualify."
    },
    "group": {
      "type": "object",
      "title": "Collapse and Expand Results",
      "properties": {
        "field": {
          "type": "string",
          "title": "Grouping Field",
          "description": "Specifies the field name(s) for grouping field operations in the document processing pipeline."
        },
        "leaderStrategy": {
          "type": "object",
          "title": "Group Leader Strategy",
          "description": "Optional selection criteria for the representative document from each group. Only one method may be used at a time. Defaults to relevancy if not specified.",
          "properties": {
            "fieldLeader": {
              "type": "object",
              "title": "By Field Value",
              "description": "Selects the document with the minimum or maximum value for the indicated field to be the representative document for each group.",
              "properties": {
                "field": {
                  "type": "string",
                  "title": "Field",
                  "description": "Specifies the field name(s) for field operations in the document processing pipeline."
                },
                "selector": {
                  "type": "string",
                  "title": "Selector",
                  "enum": ["min", "max"]
                }
              }
            },
            "sortLeader": {
              "type": "object",
              "title": "By Sort",
              "description": "Selects the representative document for each group based on the order they would be returned with the given sort criteria.",
              "properties": {
                "sort": {
                  "type": "array",
                  "title": "Sort",
                  "items": {
                    "type": "object",
                    "required": ["type"],
                    "properties": {
                      "type": {
                        "type": "string",
                        "title": "Sort Type",
                        "enum": ["field", "expression", "relevancy"],
                        "default": "field"
                      },
                      "value": {
                        "type": "string",
                        "title": "Field Name or Expression"
                      },
                      "order": {
                        "type": "string",
                        "title": "Sort Order",
                        "enum": ["asc", "desc"]
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "collapseHint": {
          "type": "string",
          "title": "Hint",
          "description": "Hint for collapse optimization.",
          "enum": ["top_fc", "block"]
        },
        "nullPolicy": {
          "type": "string",
          "title": "Null Policy",
          "description": "Instruction for handling documents with a null values in the collapse field.",
          "enum": ["expand", "collapse"]
        },
        "size": {
          "type": "integer",
          "title": "Group Size",
          "description": "The number of results per group. Value greater than 0 will expand the results."
        },
        "sort": {
          "type": "array",
          "title": "Group Sort",
          "description": "Determines the order of results within each group.",
          "items": {
            "type": "object",
            "required": ["type"],
            "properties": {
              "type": {
                "type": "string",
                "title": "Sort Type",
                "enum": ["field", "expression", "relevancy"],
                "default": "field"
              },
              "value": {
                "type": "string",
                "title": "Field Name or Expression"
              },
              "order": {
                "type": "string",
                "title": "Sort Order",
                "enum": ["asc", "desc"]
              }
            }
          }
        },
        "expandField": {
          "type": "string",
          "title": "Expand On Field",
          "description": "Specifies the field name(s) for expand on field operations in the document processing pipeline."
        },
        "expandQuery": {
          "type": "string",
          "title": "Expand Query",
          "description": "Overrides the main query (q), determines which documents to include in the main group."
        },
        "expandFq": {
          "type": "array",
          "title": "Expand Filter Queries",
          "description": "Overrides main filter queries (fq), determines which documents to include in the main group. The default is to use the main filter queries.",
          "items": {
            "type": "string"
          }
        },
        "expandNullGroup": {
          "type": "boolean",
          "title": "Expand Null Groups",
          "description": "Whether to group null values into a separate expansion."
        }
      }
    }
  },
  "category": "Set Up",
  "categoryPriority": 8,
  "unsafe": false
};

export const SchemaParamFields = ({schema}) => {
  const sanitize = str => {
    if (typeof str !== "string") return str;
    return str.replace(/^"(.*)"$/s, "$1").replace(/\\/g, "").replace(/"/g, "'");
  };
  const renderMd = str => {
    const s = sanitize(str);
    const text = (/[.!?]\)*$/).test(s) ? s : `${s}.`;
    return text.split(/(\*\*[^*]+\*\*|_[^_]+_|`[^`]+`)/g).map((part, i) => {
      if (part.startsWith("**")) return <strong key={i}>{part.slice(2, -2)}</strong>;
      if (part.startsWith("_")) return <em key={i}>{part.slice(1, -1)}</em>;
      if (part.startsWith("`")) return <code key={i}>{part.slice(1, -1)}</code>;
      return part;
    });
  };
  const {description, properties = {}, required: requiredProps = []} = schema;
  const visibleProps = useMemo(() => Object.entries(properties).filter(([, prop]) => !prop.hints?.includes("hidden")), [properties]);
  const renderProp = ([name, prop]) => {
    const isRequired = requiredProps.includes(name);
    const hasDefault = prop.default !== undefined;
    const rawDefault = prop.default;
    const hints = prop.hints || [];
    const isComplexDefault = hasDefault && (typeof rawDefault === "object" || typeof rawDefault === "string" && (rawDefault.length > 20 || rawDefault.includes('"')));
    const postBadges = [];
    if (prop.title) {
      postBadges.push(<><span className="text-stone-400 dark:text-stone-500">API property: </span>{name}</>);
    }
    const constraints = [];
    if (prop.minimum !== undefined && prop.maximum !== undefined) {
      constraints.push(`Range: ${prop.minimum} – ${prop.maximum}`);
    } else if (prop.minimum !== undefined) {
      constraints.push(`Min: ${prop.minimum}`);
    } else if (prop.maximum !== undefined) {
      constraints.push(`Max: ${prop.maximum}`);
    }
    if (prop.minLength !== undefined && prop.maxLength !== undefined) {
      constraints.push(`Length: ${prop.minLength} – ${prop.maxLength}`);
    } else if (prop.minLength !== undefined) {
      constraints.push(`Min length: ${prop.minLength}`);
    } else if (prop.maxLength !== undefined) {
      constraints.push(`Max length: ${prop.maxLength}`);
    }
    const fieldProps = {
      key: name,
      body: prop.title || name,
      type: prop.type,
      ...postBadges.length > 0 && ({
        post: postBadges
      }),
      ...isRequired && ({
        required: true
      }),
      ...!isComplexDefault && hasDefault ? {
        default: sanitize(String(rawDefault))
      } : {}
    };
    const isObject = prop.type === "object" && prop.properties;
    const isArrayOfObjects = prop.type === "array" && prop.items?.type === "object" && prop.items.properties;
    return <ParamField {...fieldProps}>
        {prop.description && <p>{renderMd(prop.description)}</p>}

        {prop.enum && <p>
            Allowed values: 
            {prop.enum.map((v, i) => <>{i > 0 && ", "}<code key={i}>{String(v)}</code></>)}
          </p>}

        {constraints.length > 0 && <p className="text-stone-500 dark:text-stone-400 text-sm">
            {constraints.join(" · ")}
          </p>}

        {isComplexDefault && <div className="flex">
            <p>
              <strong>Default:</strong>
            </p>
            <pre className="!my-0">
              <code>
                {JSON.stringify(rawDefault, null, 2)}
              </code>
            </pre>
          </div>}

        {isArrayOfObjects && <Expandable title="item properties">
            <SchemaParamFields schema={{
      properties: prop.items.properties,
      required: prop.items.required
    }} />
          </Expandable>}

        {isObject && <Expandable title="properties">
            <SchemaParamFields schema={{
      properties: prop.properties,
      required: prop.required
    }} />
          </Expandable>}
      </ParamField>;
  };
  return <div>
      {description && <p>{renderMd(description)}</p>}

      {visibleProps.map(renderProp)}
    </div>;
};

export const LwTemplate = ({title = "Key questions to get you started", icon = "sparkles", cta = "Powered by Agent Studio", linkHref = "https://lucidworks.com/demo/?utm_source=docs&utm_medium=referral&utm_campaign=docs_cta_ai"}) => {
  const [isLoaded, setIsLoaded] = useState(false);
  useEffect(() => {
    const timer = setTimeout(() => {
      setIsLoaded(true);
    }, 500);
    return () => clearTimeout(timer);
  }, []);
  return <div className="lw-template-container">
      <Card title={title} icon={icon}>
        {isLoaded && <span dangerouslySetInnerHTML={{
    __html: `<lw-template id="a029c1a9-28be-427e-b0e1-5d918920246a"></lw-template
            >`
  }} />}
        <Link href={linkHref} className="agent-studio-link text-left text-gray-600 gap-2 dark:text-gray-400 text-sm font-medium flex flex-row items-center hover:text-primary dark:hover:text-primary-light group-hover:text-primary group-hover:dark:text-primary-light">Powered by Lucidworks Agent Studio</Link>
      </Card>
    </div>;
};

[localhost link]: http://localhost:3000/docs/5/fusion/reference/config-ref/pipeline-stages/query-stages/search-fields-query-stage

[mintlify link]: https://doc.lucidworks.com/docs/5/fusion/reference/config-ref/pipeline-stages/query-stages/search-fields-query-stage

[old doc.lw link]: https://doc.lucidworks.com/fusion/5.9/289

The Query Fields query pipeline stage defines common Solr query parameters for the [edismax query parser](https://cwiki.apache.org/confluence/display/solr/The+Extended+DisMax+Query+Parser). If using a less-than sign (\<) with DisMax, it must be escaped using a backslash.
An alternative to this stage is the
[Additional Query Parameters stage](/docs/5/fusion/reference/config-ref/pipeline-stages/query-stages/set-query-params-stage).

<LwTemplate />

## Collapsing results

In Fusion 5.9.13 and up, you can configure this stage to collapse search results based on a field, such as `product_id`, to group all variations of each item into a single search result.
This is useful for ecommerce sites where you want to show a single product with multiple SKUs or variations.

Fields used for grouping must be of type string, int, or float.

1. Open your query pipeline.
2. In the Query Fields stage, select the checkbox under *Collapse and Expand Results*.
3. Under **Grouping Field**, enter the field name to group by, such as the product ID field.
4. Save the query pipeline.

By default, variations are sorted by `_score`, but you can change this to any field in the index using the options under **Group Sort**.

For additional collapse options, see the configuration reference below.

## Query pipeline stage condition examples

Stages can be triggered conditionally when a script in the **Condition** field evaluates to true.
Some examples are shown below.

Run this stage only for mobile clients:

```js wrap  theme={"dark"}
params.deviceType === "mobile"
```

Run this stage when debugging is enabled:

```js wrap  theme={"dark"}
params.debug === "true"
```

Run this stage when the query includes a specific term:

```js wrap  theme={"dark"}
params.q && params.q.includes("sale")
```

Run this stage when multiple conditions are met:

```js wrap  theme={"dark"}
request.hasParam("fusion-user-name") && request.getFirstParam("fusion-user-name").equals("SuperUser");
!request.hasParam("isFusionPluginQuery")
```

The first condition checks that the request parameter "fusion-user-name" is present and has the value "SuperUser".
The second condition checks that the request parameter "isFusionPluginQuery" is not present.

## Configuration

<Tip>
  When entering configuration values in the UI, use *unescaped* characters, such as `\t` for the tab character. When entering configuration values in the API, use *escaped* characters, such as `\\t` for the tab character.
</Tip>

<SchemaParamFields schema={schema} />
