> ## 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-to-Query Collaborative Similarity Job

export const schema = {
  "type": "object",
  "title": "Query-to-Query Collaborative Similarity (deprecated)",
  "description": "Batch-computes query-to-query similarities using ALS collaborative filtering and stores results for use in recommendations. Deprecated. Use the Query-to-Query Session-Based Similarity job instead.",
  "required": ["id", "trainingCollection", "outputQuerySimCollection", "type"],
  "properties": {
    "id": {
      "type": "string",
      "title": "Spark Job ID",
      "description": "The ID for this Spark job. Used in the API to reference this job. Allowed characters: a-z, A-Z, dash (-) and underscore (_).",
      "maxLength": 63,
      "pattern": "[a-zA-Z][_\\-a-zA-Z0-9]*[a-zA-Z0-9]?"
    },
    "sparkConfig": {
      "type": "array",
      "title": "Spark Settings",
      "description": "Spark configuration settings.",
      "hints": ["advanced"],
      "items": {
        "type": "object",
        "required": ["key"],
        "properties": {
          "key": {
            "type": "string",
            "title": "Parameter Name"
          },
          "value": {
            "type": "string",
            "title": "Parameter Value"
          }
        }
      }
    },
    "modelId": {
      "type": "string",
      "title": "Recommender Model ID",
      "description": "Specifies the unique identifier for the recommender model, used as the key when storing the model in Solr.",
      "hints": ["advanced"]
    },
    "modelCollection": {
      "type": "string",
      "title": "Model Collection",
      "description": "Specifies the collection used to load and store the computed ALS model. If absent, the model is not loaded or saved.",
      "hints": ["advanced"]
    },
    "saveModel": {
      "type": "boolean",
      "title": "Save Model in Solr",
      "description": "When enabled, saves the computed ALS model to Solr for future use.",
      "default": false,
      "hints": ["advanced"]
    },
    "trainingCollection": {
      "type": "string",
      "title": "Recommender Training Collection",
      "description": "Specifies the item or query preference collection used as training data, typically a signals or signal aggregation collection."
    },
    "trainingDataFilterQuery": {
      "type": "string",
      "title": "Training Data Filter Query",
      "description": "Filters training data using a Solr query, for example to downsample or select on minimum preference values.",
      "default": "*:*",
      "hints": ["advanced"]
    },
    "popularQueryMin": {
      "type": "integer",
      "title": "Training Data Filter By Popular Items",
      "description": "Sets the minimum number of unique users that must interact with an item for it to be included in training.",
      "default": 2,
      "hints": ["advanced"]
    },
    "trainingSampleFraction": {
      "type": "number",
      "title": "Training Data Sampling Fraction",
      "description": "Sets the fraction of preferences to sample per item. Sampled to at least 2 items per user.",
      "default": 1,
      "hints": ["advanced"],
      "maximum": 1,
      "exclusiveMaximum": false
    },
    "outputQuerySimCollection": {
      "type": "string",
      "title": "Query-to-query Similarity Collection",
      "description": "Specifies the collection where batch-computed query-to-query similarities are stored. If absent, similarities are not computed."
    },
    "outputItemsForQueriesCollection": {
      "type": "string",
      "title": "Items-for-query Boosting Collection",
      "description": "Specifies the collection where batch-computed items-for-queries recommendations are stored. If absent, recommendations are not computed."
    },
    "queryField": {
      "type": "string",
      "title": "Training Collection Query Field",
      "description": "Specifies the training collection field containing the query string.",
      "default": "query",
      "hints": ["advanced"]
    },
    "itemIdField": {
      "type": "string",
      "title": "Training Collection Item Id Field",
      "description": "Specifies the training collection field containing the item ID.",
      "default": "item_id_s",
      "hints": ["advanced"]
    },
    "weightField": {
      "type": "string",
      "title": "Training Collection Weight Field",
      "description": "Specifies the training collection field containing the interaction weight.",
      "default": "weight_d",
      "hints": ["advanced"]
    },
    "numSims": {
      "type": "integer",
      "title": "Number of Query Similarities to Compute",
      "description": "Sets the number of query similarities to compute and store per query.",
      "default": 10,
      "hints": ["advanced"]
    },
    "numItemsPerQuery": {
      "type": "integer",
      "title": "Number of Items per Query to Recommend",
      "description": "Sets the number of item recommendations to compute and store per query.",
      "default": 10,
      "hints": ["advanced"]
    },
    "initialRank": {
      "type": "integer",
      "title": "Recommender Rank",
      "description": "Sets the number of user and item factors in the ALS decomposition, or the starting value for parameter grid search.",
      "default": 100,
      "hints": ["advanced"]
    },
    "initialBlocks": {
      "type": "integer",
      "title": "Training Block Size",
      "description": "Sets the number of sub-matrix blocks for the training data. Use `-1` for automatic sizing.",
      "default": -1,
      "hints": ["hidden"]
    },
    "maxTrainingIterations": {
      "type": "integer",
      "title": "Maximum Training Iterations",
      "description": "Sets the maximum number of iterations for learning the ALS matrix decomposition.",
      "default": 10,
      "hints": ["advanced"]
    },
    "initialAlpha": {
      "type": "number",
      "title": "Implicit Preference Confidence",
      "description": "Sets the confidence weight given to implicit preferences, or the starting value for parameter grid search.",
      "default": 0.5,
      "hints": ["advanced"]
    },
    "initialLambda": {
      "type": "number",
      "title": "Smoothing",
      "description": "Sets the regularization parameter to prevent overfitting, or the starting value for parameter grid search.",
      "default": 0.01,
      "hints": ["advanced"]
    },
    "gridSearchWidth": {
      "type": "integer",
      "title": "Grid Search Width",
      "description": "Sets the width of the exponential parameter grid search centered around the initial parameter guesses.",
      "default": 1,
      "hints": ["advanced"]
    },
    "randomSeed": {
      "type": "integer",
      "title": "Random Seed",
      "description": "Sets the random seed for deterministic operations including sampling and initialization. Fix this value to reproduce identical results across runs.",
      "default": 13,
      "hints": ["advanced"]
    },
    "implicitRatings": {
      "type": "boolean",
      "title": "Implicit Preferences",
      "description": "When enabled, treats training preferences as implicit signals such as clicks rather than explicit ratings.",
      "default": true
    },
    "alwaysTrain": {
      "type": "boolean",
      "title": "Force model re-training",
      "description": "When enabled, retrains the model even if a model with the same ID already exists.",
      "default": true
    },
    "trainingDataFrameConfigOptions": {
      "type": "object",
      "title": "Dataframe Config Options",
      "description": "Sets additional key-value configuration options passed to the Spark DataFrame reader at load time.",
      "properties": {},
      "additionalProperties": {
        "type": "string"
      },
      "hints": ["advanced"]
    },
    "writeOptions": {
      "type": "array",
      "title": "Write Options",
      "description": "Sets additional key-value options passed to the Spark writer when writing output to Solr or other sinks.",
      "hints": ["advanced"],
      "items": {
        "type": "object",
        "required": ["key"],
        "properties": {
          "key": {
            "type": "string",
            "title": "Parameter Name"
          },
          "value": {
            "type": "string",
            "title": "Parameter Value"
          }
        }
      }
    },
    "type": {
      "type": "string",
      "title": "Spark Job Type",
      "enum": ["query_similarity"],
      "default": "query_similarity",
      "hints": ["readonly"]
    }
  },
  "additionalProperties": true,
  "category": "Other",
  "categoryPriority": 1,
  "propertyGroups": [{
    "label": "Input/Output Parameters",
    "properties": ["trainingCollection", "trainingDataFilterQuery", "modelCollection", "outputItemsForQueriesCollection", "outputQuerySimCollection", "writeOptions", "trainingDataFrameConfigOptions", "trainingSampleFraction", "randomSeed"]
  }, {
    "label": "Field Parameters",
    "properties": ["queryField", "itemIdField", "weightField"]
  }, {
    "label": "Model Tuning Parameters",
    "properties": ["alwaysTrain", "saveModel", "gridSearchWidth", "implicitRatings", "initialAlpha", "initialLambda", "initialRank", "maxTrainingIterations", "numItemsPerQuery", "numSims", "popularQueryMin"]
  }, {
    "label": "Misc. Parameters",
    "properties": ["modelId"]
  }]
};

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/jobs/query-to-query-collaborative-similarity

[mintlify link]: https://doc.lucidworks.com/docs/5/fusion/reference/config-ref/jobs/query-to-query-collaborative-similarity

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

Train a collaborative filtering matrix decomposition recommender using [SparkML’s Alternating Least Squares (ALS)](https://spark.apache.org/docs/latest/ml-collaborative-filtering.html) to batch-compute query-query similarities. This can be used for [items-for-query recommendations](/docs/5/fusion/getting-data-out/query-enhancement/recommendations/items-for-query) as well as [queries-for-query recommendations](/docs/5/fusion/getting-data-out/query-enhancement/recommendations/queries-for-query).

|                          | query | count\_i | type | timestamp\_tdt | user\_id | doc\_id | session\_id | fusion\_query\_id |
| ------------------------ | ----- | -------- | ---- | -------------- | -------- | ------- | ----------- | ----------------- |
| Required signals fields: | ✅     | ✅        | ✅    | ✅              | ✅        |         |             |                   |

<LwTemplate />

## Configuration properties

<SchemaParamFields schema={schema} />
