> ## 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.

# Recommend Items for Item

> Query pipeline stage configuration specifications

export const schema = {
  "type": "object",
  "title": "Recommend Items for Item",
  "description": "Returns item-to-item recommendations for a given item or applies recommendation scores as boosts to the main query.",
  "required": ["boostingMethod", "boostingParam"],
  "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"]
    },
    "numRecommendations": {
      "type": "integer",
      "title": "Number of Recommendations",
      "default": 10
    },
    "modelID": {
      "type": "string",
      "title": "Model ID",
      "default": "*",
      "description": "Specifies the ID of the recommendation model to use. Default is `*` to use the most recently trained model."
    },
    "collection": {
      "type": "string",
      "title": "Recommendation Collection",
      "description": "Specifies the Solr collection queried for recommendations. Must exactly match an existing collection name."
    },
    "resultsLocation": {
      "type": "string",
      "title": "Results Location",
      "description": "Specifies where recommendation results are stored. Use `As Response` to return them directly. Otherwise, results are stored in the context under `resultsKey`.",
      "enum": ["As Boosts", "As Response"],
      "default": "As Boosts"
    },
    "modelIdField": {
      "type": "string",
      "title": "Model ID Field",
      "description": "Specifies the document field containing the model ID. Default is `modelId`.",
      "default": "modelId",
      "hints": ["advanced"]
    },
    "scaleRange": {
      "type": "object",
      "title": "Scale Boosts",
      "description": "Scales boost values to a specified `[min, max]` range before applying them.",
      "required": ["scaleMin", "scaleMax"],
      "properties": {
        "scaleMin": {
          "type": "number",
          "title": "Minimum value of the scale range",
          "description": "Threshold or limit value for minimum value of the scale range. Values outside this threshold trigger different processing behavior. Numeric value with valid range determined by operational context."
        },
        "scaleMax": {
          "type": "number",
          "title": "Maximum value of the scale range",
          "description": "Threshold or limit value for maximum value of the scale range. Values outside this threshold trigger different processing behavior. Numeric value with valid range determined by operational context."
        }
      },
      "hints": ["advanced"]
    },
    "foldInUpdates": {
      "type": "boolean",
      "title": "Estimate Recent Results",
      "description": "When enabled, incorporates recent user activity since the last recommendation job run into the recommendations.",
      "hints": ["advanced"]
    },
    "boostFieldName": {
      "type": "string",
      "title": "Boost Field",
      "description": "Specifies the Solr field used to match documents for boosting.",
      "default": "id",
      "hints": ["advanced"]
    },
    "boostingMethod": {
      "type": "string",
      "title": "Boost Method",
      "description": "Specifies the boost method. Use `query-parser` when `defType` is not `edismax` for the main query.",
      "enum": ["query-param", "query-parser"],
      "default": "query-param",
      "hints": ["advanced"]
    },
    "boostingParam": {
      "type": "string",
      "title": "Boost Param",
      "description": "Specifies whether `boost` multiplies scores by boost values or `bq` adds optional clauses to the main query.",
      "enum": ["boost", "bq"],
      "default": "boost",
      "hints": ["advanced"]
    },
    "routingParams": {
      "type": "array",
      "title": "Additional query params for routing",
      "description": "Specifies routing parameters such as `lw.nodeFilter` to direct recommender queries to specific nodes.",
      "hints": ["advanced"],
      "items": {
        "type": "object",
        "required": ["key"],
        "properties": {
          "key": {
            "type": "string",
            "title": "Parameter Name"
          },
          "value": {
            "type": "string",
            "title": "Parameter Value"
          }
        }
      }
    },
    "itemIdParam": {
      "type": "string",
      "title": "Item ID Request Parameter",
      "description": "Specifies the request parameter name containing the item ID used for item-to-item recommendations.",
      "default": "item_id"
    },
    "itemIdField": {
      "type": "string",
      "title": "Item ID Field",
      "description": "Specifies the document field containing the item ID. Default is `itemId`.",
      "default": "itemId",
      "hints": ["advanced"]
    },
    "otherItemIdField": {
      "type": "string",
      "title": "Recommended item ID Field",
      "description": "Specifies the document field containing the recommended item ID. Default is `otherItemId`.",
      "default": "otherItemId",
      "hints": ["advanced"]
    },
    "similarityScoreField": {
      "type": "string",
      "title": "Similarity Score Field",
      "description": "Specifies the document field containing the similarity score between items. Default is `sim`.",
      "default": "sim",
      "hints": ["advanced"]
    }
  },
  "category": "Results Relevancy",
  "categoryPriority": 7,
  "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/lucidworks-search/09-developer-documentation/config-specs/query-pipeline-stages/recommend-items-for-item

[mintlify link]: https://doc.lucidworks.com/docs/lucidworks-search/09-developer-documentation/config-specs/query-pipeline-stages/recommend-items-for-item

[old doc.lw link]: https://doc.lucidworks.com/managed-fusion/5.9/hq339y

The Recommend Items for Item query pipeline stage uses signals about users' item choices to recommend related items based on a specific item. Relationships between items can be based on different criteria, such as click patterns, people who bought this also bought that, percentage match of document tags, and so on.

Given an item ID, this stage performs a secondary query to the `COLLECTION_NAME_items_for_item_recommendations` collection to find related items, then retrieves those items from the main collection.

This pipeline stage uses items-for-item recommendations that have been precomputed by the [BPR Recommender](/docs/lucidworks-search/09-developer-documentation/config-specs/jobs/bpr-recommender).

**See also [Items-for-item Recommendations](/docs/lucidworks-search/07-improve-your-queries/recommendations/items-for-item) to learn how to configure this recommender type and fetch recommendations.**

<LwTemplate />

## Prerequisites

**Enable recommendations:**

Before creating a Recommend Items for Item stage, enable recommendations.

* **Lucidworks Search UI** – In Collections Manager, click the settings icon next to the collection > **Enable Recommendations**.
* **Using the REST API** – Use this command to enable recommendations:

  ```bash wrap theme={"dark"}
  curl -u USERNAME:PASSWORD -X PUT http://EXAMPLE_COMPANY.lucidworks.cloud/api/v1/collections/COLLECTION_NAME/features/recommendations -H 'content-type: application/json' -d '{"enabled":true}'
  ```

<Note>
  Replace `EXAMPLE_COMPANY` with the name provided by your Lucidworks representative.
</Note>

<Note>
  When you enable recommendations, Lucidworks Search creates a query pipeline that already contains this stage, and that is configured for boosting. The query pipeline is `COLLECTION_NAME_items_for_item_recommendations`.
</Note>

## Using live signals

The **Estimate Recent Results** option uses live signals to augment items-for-user recommendations with real-time recommendations.

When this is enabled, Lucidworks Search first looks up items (from previously-generated recommendations) that are similar to the new items. If there are none then it looks up similar users (who also interacted with that item) to get a list of recommendations based on the new items. It then combines those new recommendations with the job-based recommendations already generated for that user (if any), to generate a final list of recommendations.

## 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} />
