ercsonusharma commented on code in PR #3418: URL: https://github.com/apache/solr/pull/3418#discussion_r2286964590
########## solr/core/src/java/org/apache/solr/search/combine/ReciprocalRankFusion.java: ########## @@ -0,0 +1,252 @@ +/* + * 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.solr.search.combine; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.StringJoiner; +import org.apache.lucene.document.Document; +import org.apache.lucene.search.Explanation; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.TotalHits; +import org.apache.solr.common.params.CombinerParams; +import org.apache.solr.common.params.SolrParams; +import org.apache.solr.common.util.NamedList; +import org.apache.solr.common.util.SimpleOrderedMap; +import org.apache.solr.handler.component.ShardDoc; +import org.apache.solr.schema.IndexSchema; +import org.apache.solr.search.DocIterator; +import org.apache.solr.search.DocList; +import org.apache.solr.search.DocSlice; +import org.apache.solr.search.QueryResult; +import org.apache.solr.search.SolrDocumentFetcher; +import org.apache.solr.search.SolrIndexSearcher; +import org.apache.solr.search.SortedIntDocSet; + +/** + * The ReciprocalRankFusion class implements a query and response combiner that uses the Reciprocal + * Rank Fusion (RRF) algorithm to combine multiple ranked lists into a single ranked list. + */ +public class ReciprocalRankFusion extends QueryAndResponseCombiner { + + private int k; + + public int getK() { + return k; + } + + public ReciprocalRankFusion() { + this.k = CombinerParams.COMBINER_RRF_K_DEFAULT; + } + + @Override + public void init(NamedList<?> args) { + Object kParam = args.get("k"); + if (kParam != null) { + this.k = Integer.parseInt(kParam.toString()); + } + } + + @Override + public QueryResult combine(List<QueryResult> rankedLists, SolrParams solrParams) { + int kVal = solrParams.getInt(CombinerParams.COMBINER_RRF_K, this.k); + List<DocList> docLists = getDocListsFromQueryResults(rankedLists); + QueryResult combinedResult = new QueryResult(); + combineResults(combinedResult, docLists, false, kVal); + return combinedResult; + } + + private static List<DocList> getDocListsFromQueryResults(List<QueryResult> rankedLists) { + List<DocList> docLists = new ArrayList<>(rankedLists.size()); + for (QueryResult rankedList : rankedLists) { + docLists.add(rankedList.getDocList()); + } + return docLists; + } + + @Override + public List<ShardDoc> combine(Map<String, List<ShardDoc>> shardDocMap, SolrParams solrParams) { + int kVal = solrParams.getInt(CombinerParams.COMBINER_RRF_K, this.k); + HashMap<String, Float> docIdToScore = new HashMap<>(); + Map<String, ShardDoc> docIdToShardDoc = new HashMap<>(); + List<ShardDoc> finalShardDocList = new ArrayList<>(); + for (Map.Entry<String, List<ShardDoc>> shardDocEntry : shardDocMap.entrySet()) { + List<ShardDoc> shardDocList = shardDocEntry.getValue(); + int ranking = 1; + while (ranking <= shardDocList.size()) { + String docId = shardDocList.get(ranking - 1).id.toString(); + docIdToShardDoc.put(docId, shardDocList.get(ranking - 1)); + float rrfScore = 1f / (kVal + ranking); + docIdToScore.compute(docId, (id, score) -> (score == null) ? rrfScore : score + rrfScore); + ranking++; + } + } + List<Map.Entry<String, Float>> sortedByScoreDescending = + docIdToScore.entrySet().stream() + .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) + .toList(); + for (Map.Entry<String, Float> scoredDoc : sortedByScoreDescending) { + String docId = scoredDoc.getKey(); + Float score = scoredDoc.getValue(); + ShardDoc shardDoc = docIdToShardDoc.get(docId); + shardDoc.score = score; + finalShardDocList.add(shardDoc); + } + return finalShardDocList; + } + + private Map<Integer, Integer[]> combineResults( + QueryResult combinedRankedList, + List<DocList> rankedLists, + boolean saveRankPositionsForExplain, + int kVal) { + Map<Integer, Integer[]> docIdToRanks = null; + HashMap<Integer, Float> docIdToScore = new HashMap<>(); + long totalMatches = 0; + for (DocList rankedList : rankedLists) { + DocIterator docs = rankedList.iterator(); + totalMatches = Math.max(totalMatches, rankedList.matches()); + int ranking = 1; + while (docs.hasNext()) { + int docId = docs.nextDoc(); + float rrfScore = 1f / (kVal + ranking); + docIdToScore.compute(docId, (id, score) -> (score == null) ? rrfScore : score + rrfScore); + ranking++; + } + } + List<Map.Entry<Integer, Float>> sortedByScoreDescending = + docIdToScore.entrySet().stream() + .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) + .toList(); + + int combinedResultsLength = docIdToScore.size(); + int[] combinedResultsDocIds = new int[combinedResultsLength]; + float[] combinedResultScores = new float[combinedResultsLength]; + + int i = 0; + for (Map.Entry<Integer, Float> scoredDoc : sortedByScoreDescending) { + combinedResultsDocIds[i] = scoredDoc.getKey(); + combinedResultScores[i] = scoredDoc.getValue(); + i++; + } + + if (saveRankPositionsForExplain) { + docIdToRanks = getRanks(rankedLists, combinedResultsDocIds); + } + + DocSlice combinedResultSlice = + new DocSlice( + 0, + combinedResultsLength, + combinedResultsDocIds, + combinedResultScores, + Math.max(combinedResultsLength, totalMatches), + combinedResultScores.length > 0 ? combinedResultScores[0] : 0, + TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO); + combinedRankedList.setDocList(combinedResultSlice); + SortedIntDocSet docSet = new SortedIntDocSet(combinedResultsDocIds, combinedResultsLength); Review Comment: > Solr DocSet is used to hold all doc IDs that match a query, ignoring rows or start params Absolutely Right! > It's only for a non-distrib request (distrib=false) It's for distributed as well as distributed request, both have to go through this phase through ShardHandlerRequest. Only difference being that it sets the start=0 and row+=start. Then, final merge happens after collecting the results from all ShardHandlers. Am I right? This method is invoked right after the SolrSearchIndexer call for all the sub-queries. It's not creating DocSet rather modifying the existing one, returned from SolrSearchIndexer. The complete flow is like: 1. Prepare all the sub-queries in terms of parsing basis the QueryParser. 2. Process all the sub-queries by sending it across the SolrSearchIndexer which will return the `QueryResult` having `DocSet`. 3. The `ReciprocalRankFusion` then rescores them and creates a modified `DocSet`. Let me know if that makes sense. -- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
