rahil-c commented on code in PR #18432: URL: https://github.com/apache/hudi/pull/18432#discussion_r3037505753
########## hudi-spark-datasource/hudi-spark-common/src/main/scala/org/apache/spark/sql/hudi/analysis/HoodieVectorSearchPlanBuilder.scala: ########## @@ -0,0 +1,325 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.hudi.analysis + +import org.apache.hudi.common.schema.HoodieSchema + +import org.apache.spark.sql.{DataFrame, SparkSession} +import org.apache.spark.sql.catalyst.plans.logical.HoodieVectorSearchTableValuedFunction.{DistanceMetric, SearchAlgorithm} +import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan +import org.apache.spark.sql.expressions.Window +import org.apache.spark.sql.functions.{broadcast, col, monotonically_increasing_id, row_number} +import org.apache.spark.sql.hudi.command.exception.HoodieAnalysisException +import org.apache.spark.sql.types.{ArrayType, ByteType, DataType, DoubleType, FloatType} + +import scala.util.{Failure, Success, Try} + +/** + * Extension point for vector search algorithms. Each implementation provides + * the Spark logical plan for single-query and batch-query KNN search. + * + * To add a new algorithm (e.g. RowMatrix, HNSW): + * 1. Create an object extending this trait + * 2. Add a value to [[SearchAlgorithm]] + * 3. Register the mapping in [[HoodieVectorSearchPlanBuilder.resolveAlgorithm]] + * + * Implementations can use the shared validation helpers on + * [[HoodieVectorSearchPlanBuilder]] (validateEmbeddingColumn, validateBatchDimensions, etc.) + * and the raw distance functions on [[VectorDistanceUtils]]. + * + * The output schema contract: + * - Single-query: all corpus columns (minus the embedding column) + `_hudi_distance: Double` + * - Batch-query: all corpus columns (minus the embedding column) + clashing query columns + * (prefixed with `_hudi_query_`) + `_hudi_distance: Double` + `_hudi_query_index: Long` + * - Results are ordered by `_hudi_distance` ascending (lower = more similar) + * - `_hudi_query_index` is an opaque grouping identifier (not a sequential index). Values may be + * large non-contiguous numbers because they are generated by `monotonically_increasing_id()`. + */ +trait VectorSearchAlgorithm { + + /** Human-readable name for error messages and logging. */ + def name: String + + /** + * Build a plan that finds the k nearest corpus rows to a single query vector. + * + * @param spark active SparkSession + * @param corpusDf resolved corpus DataFrame (may be Hudi, Parquet, or temp view) + * @param embeddingCol name of the array-typed embedding column in corpusDf + * @param queryVector the query vector, normalized to Array[Double] + * @param k number of nearest neighbors to return + * @param metric distance metric (COSINE, L2, DOT_PRODUCT) + * @return an analyzed LogicalPlan whose output matches the single-query schema contract + */ + def buildSingleQueryPlan( + spark: SparkSession, + corpusDf: DataFrame, + embeddingCol: String, + queryVector: Array[Double], + k: Int, + metric: DistanceMetric.Value): LogicalPlan + + /** + * Build a plan that finds the k nearest corpus rows for each row in the query table. + * + * @param spark active SparkSession + * @param corpusDf resolved corpus DataFrame + * @param corpusEmbeddingCol name of the embedding column in corpusDf + * @param queryDf resolved query DataFrame + * @param queryEmbeddingCol name of the embedding column in queryDf + * @param k number of nearest neighbors per query + * @param metric distance metric (COSINE, L2, DOT_PRODUCT) + * @return an analyzed LogicalPlan whose output matches the batch-query schema contract + * @note Batch mode broadcasts the query table to all executors via a cross-join. + * This is designed for small-to-medium query sets (tens to low hundreds of rows). + * For large query tables, memory pressure on executors may occur. + */ + def buildBatchQueryPlan( + spark: SparkSession, + corpusDf: DataFrame, + corpusEmbeddingCol: String, + queryDf: DataFrame, + queryEmbeddingCol: String, + k: Int, + metric: DistanceMetric.Value): LogicalPlan +} + +/** + * Resolves [[SearchAlgorithm]] values to [[VectorSearchAlgorithm]] implementations + * and provides shared validation helpers used across algorithms. + */ +object HoodieVectorSearchPlanBuilder { + + val DISTANCE_COL = "_hudi_distance" + private[analysis] val QUERY_ID_COL = "_hudi_query_index" + private[analysis] val QUERY_EMB_ALIAS = "_hudi_query_emb" + private[analysis] val RANK_COL = "_hudi_rank" + private[analysis] val QUERY_COL_PREFIX = "_hudi_query_" + + /** Resolve a [[SearchAlgorithm]] enum value to its implementation. */ + def resolveAlgorithm(algorithm: SearchAlgorithm.Value): VectorSearchAlgorithm = algorithm match { + case SearchAlgorithm.BRUTE_FORCE => BruteForceSearchAlgorithm + case other => throw new HoodieAnalysisException( + s"Unsupported search algorithm: $other") + } + + private[analysis] def validateEmbeddingColumn(df: DataFrame, colName: String): Unit = { + val fieldOpt = df.schema.fields.find(_.name == colName) + val field = fieldOpt.getOrElse( Review Comment: addressed -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
