> ## 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": "Configure query parameters for Solr search",
  "properties": {
    "skip": {
      "type": "boolean",
      "title": "Skip This Stage",
      "description": "Set to true to skip this stage.",
      "default": false,
      "hints": ["advanced"]
    },
    "label": {
      "type": "string",
      "title": "Label",
      "description": "A unique label for this stage.",
      "hints": ["advanced"],
      "maxLength": 255
    },
    "condition": {
      "type": "string",
      "title": "Condition",
      "description": "Define a conditional script that must result in true or false. This can be used to determine if the stage should process or not.",
      "hints": ["code", "code/javascript", "advanced"]
    },
    "legacy": {
      "type": "boolean",
      "title": "Legacy",
      "description": "True if this stage only supports legacy mode",
      "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"
          },
          "boost": {
            "type": "number",
            "title": "Field Boost"
          }
        }
      }
    },
    "returnFields": {
      "type": "array",
      "title": "Return Fields",
      "items": {
        "type": "string"
      }
    },
    "returnScore": {
      "type": "boolean",
      "title": "Return Score",
      "default": true
    },
    "minimumMatch": {
      "type": "string",
      "title": "Minimum Should Match"
    },
    "group": {
      "type": "object",
      "title": "Collapse and Expand Results",
      "properties": {
        "field": {
          "type": "string",
          "title": "Grouping Field"
        },
        "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"
                },
                "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": "Field used for expansion. The default is to use the main group field."
        },
        "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 formatDescription = str => {
    const s = sanitize(str);
    return (/[.!?]\)*$/).test(s) ? s : `${s}.`;
  };
  const {description, properties = {}, required: requiredProps = []} = schema;
  const visibleProps = useMemo(() => Object.entries(properties).filter(([, prop]) => !prop.hints?.includes("hidden")), [properties]);
  return <div>
      {description && <p>{formatDescription(description)}</p>}

      {visibleProps.map(([name, prop]) => {
    const isRequired = requiredProps.includes(name);
    const hasDefault = prop.default !== undefined;
    const rawDefault = prop.default;
    const isComplexDefault = hasDefault && (typeof rawDefault === "object" || typeof rawDefault === "string" && (rawDefault.length > 20 || rawDefault.includes('"')));
    const fieldProps = {
      key: name,
      body: prop.title || name,
      type: prop.type,
      ...prop.title && ({
        post: [<><span className="text-stone-400 dark:text-stone-500">API property: </span>{name}</>]
      }),
      ...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>{formatDescription(prop.description)}</p>}

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

            {isArrayOfObjects && <div className="flex">
              <p>
                <strong>Object attributes:</strong>
              </p>
              <pre className="!my-0">
                <code>
                  {'{\n'}
                  {Object.entries(prop.items.properties).map(([iname, iprop]) => <>
                      {`  ${iname}`}
                      {prop.items?.required?.includes(iname) && <span style={{
      color: 'red'
    }}> required</span>}
                      {`: {\n    display name: ${sanitize(iprop.title || '')}\n    type: ${iprop.type}\n  }\n`}
                    </>)}
                  {'}'}
                </code>
              </pre>
              </div>}

            {isObject && <Expandable title="properties">
                <SchemaParamFields schema={{
      properties: prop.properties,
      required: prop.required
    }} />
              </Expandable>}
          </ParamField>;
  })}
    </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} />
