Example usage for org.apache.solr.common.params DisMaxParams BF

List of usage examples for org.apache.solr.common.params DisMaxParams BF

Introduction

In this page you can find the example usage for org.apache.solr.common.params DisMaxParams BF.

Prototype

String BF

To view the source code for org.apache.solr.common.params DisMaxParams BF.

Click Source Link

Document

query and init param for boosting functions

Usage

From source file:RankingSolr_p.java

License:Open Source License

public static serverObjects respond(@SuppressWarnings("unused") final RequestHeader header,
        final serverObjects post, final serverSwitch env) {
    final Switchboard sb = (Switchboard) env;

    // clean up all search events
    SearchEventCache.cleanupEvents(true);
    sb.index.clearCaches(); // every time the ranking is changed we need to remove old orderings

    int profileNr = 0;
    if (post != null)
        profileNr = post.getInt("profileNr", profileNr);

    if (post != null && post.containsKey("EnterBoosts")) {
        StringBuilder boostString = new StringBuilder(); // SwitchboardConstants.SEARCH_RANKING_SOLR_BOOST;
        for (Map.Entry<String, String> entry : post.entrySet()) {
            if (entry.getKey().startsWith("boost")) {
                String fieldName = entry.getKey().substring(6);
                CollectionSchema field = CollectionSchema.valueOf(fieldName);
                if (field == null)
                    continue;
                String fieldValue = entry.getValue();
                if (fieldValue == null || fieldValue.length() == 0)
                    continue;
                try {
                    float boost = Float.parseFloat(fieldValue);
                    if (boost > 0.0f) { // don't allow <= 0
                        if (boostString.length() > 0)
                            boostString.append(',');
                        boostString.append(field.getSolrFieldName()).append('^').append(Float.toString(boost));
                    }/*from  w ww  .  j  a  va 2s . c  om*/
                } catch (final NumberFormatException e) {
                    continue;
                }
            }
        }
        if (boostString.length() > 0) {
            String s = boostString.toString();
            sb.setConfig(SwitchboardConstants.SEARCH_RANKING_SOLR_COLLECTION_BOOSTFIELDS_ + profileNr, s);
            sb.index.fulltext().getDefaultConfiguration().getRanking(profileNr).updateBoosts(s);
        }
    }
    if (post != null && post.containsKey("ResetBoosts")) {
        String s = "url_paths_sxt^3.0,synonyms_sxt^0.5,title^5.0,text_t^1.0,host_s^6.0,h1_txt^5.0,url_file_name_tokens_t^4.0,h2_txt^3.0,keywords^2.0,description_txt^1.5,author^1.0";
        sb.setConfig(SwitchboardConstants.SEARCH_RANKING_SOLR_COLLECTION_BOOSTFIELDS_ + profileNr, s);
        sb.index.fulltext().getDefaultConfiguration().getRanking(profileNr).updateBoosts(s);
    }

    if (post != null && post.containsKey("EnterBQ")) {
        String bq = post.get(DisMaxParams.BQ);
        if (bq != null) {
            sb.setConfig(SwitchboardConstants.SEARCH_RANKING_SOLR_COLLECTION_BOOSTQUERY_ + profileNr, bq);
            sb.index.fulltext().getDefaultConfiguration().getRanking(profileNr).setBoostQuery(bq);
        }
    }
    if (post != null && post.containsKey("ResetBQ")) {
        String bq = "crawldepth_i:0^0.8 crawldepth_i:1^0.4";
        if (bq != null) {
            sb.setConfig(SwitchboardConstants.SEARCH_RANKING_SOLR_COLLECTION_BOOSTQUERY_ + profileNr, bq);
            sb.index.fulltext().getDefaultConfiguration().getRanking(profileNr).setBoostQuery(bq);
        }
    }

    if (post != null && post.containsKey("EnterFQ")) {
        String fq = post.get(CommonParams.FQ);
        if (fq != null) {
            sb.setConfig(SwitchboardConstants.SEARCH_RANKING_SOLR_COLLECTION_FILTERQUERY_ + profileNr, fq);
            sb.index.fulltext().getDefaultConfiguration().getRanking(profileNr).setFilterQuery(fq);
        }
    }
    if (post != null && post.containsKey("ResetFQ")) {
        String fq = ""; // i.e. "http_unique_b:true AND www_unique_b:true"
        if (fq != null) {
            sb.setConfig(SwitchboardConstants.SEARCH_RANKING_SOLR_COLLECTION_FILTERQUERY_ + profileNr, fq);
            sb.index.fulltext().getDefaultConfiguration().getRanking(profileNr).setFilterQuery(fq);
        }
    }

    if (post != null && post.containsKey("EnterBF")) {
        String bf = post.get(DisMaxParams.BF);
        if (bf != null) {
            sb.setConfig(SwitchboardConstants.SEARCH_RANKING_SOLR_COLLECTION_BOOSTFUNCTION_ + profileNr, bf);
            sb.index.fulltext().getDefaultConfiguration().getRanking(profileNr).setBoostFunction(bf);
        }
    }
    if (post != null && post.containsKey("ResetBF")) {
        String bf = "";
        if (bf != null) {
            sb.setConfig(SwitchboardConstants.SEARCH_RANKING_SOLR_COLLECTION_BOOSTFUNCTION_ + profileNr, bf);
            sb.index.fulltext().getDefaultConfiguration().getRanking(profileNr).setBoostFunction(bf);
        }
    }

    final serverObjects prop = new serverObjects();
    int i = 0;

    CollectionConfiguration colcfg = sb.index.fulltext().getDefaultConfiguration();
    Ranking ranking = colcfg.getRanking(profileNr);
    for (SchemaDeclaration field : CollectionSchema.values()) {
        if (!field.isSearchable())
            continue;
        Float boost = ranking.getFieldBoost(field);
        if (boost != null || colcfg.contains(field)) { // show only available or configured boost fields
            prop.put("boosts_" + i + "_field", field.getSolrFieldName());
            if (boost == null || boost.floatValue() <= 0.0f) {
                prop.put("boosts_" + i + "_checked", 0);
                prop.put("boosts_" + i + "_boost", "");
                prop.put("boosts_" + i + "_notinindexwarning", "0");
            } else {
                prop.put("boosts_" + i + "_checked", 1);
                prop.put("boosts_" + i + "_boost", boost.toString());
                prop.put("boosts_" + i + "_notinindexwarning", (colcfg.contains(field.name()) ? "0" : "1"));
            }
            prop.putHTML("boosts_" + i + "_comment", field.getComment());
            i++;
        }
    }
    prop.put("boosts", i);
    prop.put(CommonParams.FQ, ranking.getFilterQuery());
    prop.put(DisMaxParams.BQ, ranking.getBoostQuery());
    prop.put(DisMaxParams.BF, ranking.getBoostFunction());

    for (int j = 0; j < 4; j++) {
        prop.put("profiles_" + j + "_nr", j);
        prop.put("profiles_" + j + "_name",
                sb.getConfig(SwitchboardConstants.SEARCH_RANKING_SOLR_COLLECTION_BOOSTNAME_ + j, "N.N."));
        prop.put("profiles_" + j + "_selected", profileNr == j ? 1 : 0);
    }
    prop.put("profiles", 4);
    prop.put("profileNr", profileNr);

    // make boost hints for vocabularies
    Map<String, ReversibleScoreMap<String>> vocabularyFacet;
    try {
        vocabularyFacet = sb.index.fulltext().getDefaultConnector().getFacets(
                CollectionSchema.vocabularies_sxt.getSolrFieldName() + AbstractSolrConnector.CATCHALL_DTERM,
                100, CollectionSchema.vocabularies_sxt.getSolrFieldName());
    } catch (IOException e) {
        ConcurrentLog.logException(e);
        vocabularyFacet = new HashMap<>();
    }
    if (vocabularyFacet.size() == 0) {
        prop.put("boosthint", 0);
    } else {
        prop.put("boosthint", 1);
        prop.putHTML("boosthint_vocabulariesfield", CollectionSchema.vocabularies_sxt.getSolrFieldName());
        ReversibleScoreMap<String> vokcounts = vocabularyFacet.values().iterator().next();
        Collection<String> vocnames = vokcounts.keyList(true);
        prop.putHTML("boosthint_vocabulariesavailable", vocnames.toString());
        ArrayList<String> voccountFields = new ArrayList<>();
        ArrayList<String> voclogcountFields = new ArrayList<>();
        ArrayList<String> voclogcountsFields = new ArrayList<>();
        ArrayList<String> ff = new ArrayList<>();
        for (String vocname : vocnames) {
            voccountFields.add(
                    CollectionSchema.VOCABULARY_PREFIX + vocname + CollectionSchema.VOCABULARY_COUNT_SUFFIX);
            voclogcountFields.add(
                    CollectionSchema.VOCABULARY_PREFIX + vocname + CollectionSchema.VOCABULARY_LOGCOUNT_SUFFIX);
            voclogcountsFields.add(CollectionSchema.VOCABULARY_PREFIX + vocname
                    + CollectionSchema.VOCABULARY_LOGCOUNTS_SUFFIX);
        }
        ff.addAll(voclogcountFields);
        ff.addAll(voclogcountsFields);
        prop.putHTML("boosthint_vocabulariesvoccount", voccountFields.toString());
        prop.putHTML("boosthint_vocabulariesvoclogcount", voclogcountFields.toString());
        prop.putHTML("boosthint_vocabulariesvoclogcounts", voclogcountsFields.toString());
        String[] facetfields = ff.toArray(new String[ff.size()]);
        int fc = 0;
        if (facetfields.length > 0)
            try {
                LinkedHashMap<String, ReversibleScoreMap<String>> facets = sb.index.fulltext()
                        .getDefaultConnector().getFacets("*:*", 100, facetfields);
                facets.put(CollectionSchema.vocabularies_sxt.getSolrFieldName(), vokcounts);
                for (Map.Entry<String, ReversibleScoreMap<String>> facetentry : facets.entrySet()) {
                    ReversibleScoreMap<String> facetfieldmap = facetentry.getValue();
                    if (facetfieldmap.size() == 0)
                        continue;
                    TreeMap<String, Integer> statMap = new TreeMap<>();
                    for (String k : facetfieldmap)
                        statMap.put(k, facetfieldmap.get(k));
                    prop.put("boosthint_facets_" + fc + "_facetname", facetentry.getKey());
                    int c = 0;
                    for (Entry<String, Integer> entry : statMap.entrySet()) {
                        prop.put("boosthint_facets_" + fc + "_facet_" + c + "_key", entry.getKey());
                        prop.put("boosthint_facets_" + fc + "_facet_" + c + "_count", entry.getValue());
                        c++;
                    }
                    prop.put("boosthint_facets_" + fc + "_facet", c);
                    fc++;
                }
            } catch (IOException e) {
            }
        prop.put("boosthint_facets", fc);
    }

    return prop;
}

From source file:net.yacy.http.servlets.SolrSelectServlet.java

License:Open Source License

@Override
public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {

    HttpServletRequest hrequest = (HttpServletRequest) request;
    HttpServletResponse hresponse = (HttpServletResponse) response;
    SolrQueryRequest req = null;//  w  ww.  j  ava 2 s.c  om

    final Method reqMethod = Method.getMethod(hrequest.getMethod());

    Writer out = null;
    try {
        // prepare request to solr
        MultiMapSolrParams mmsp = SolrRequestParsers.parseQueryString(hrequest.getQueryString());

        Switchboard sb = Switchboard.getSwitchboard();
        boolean authenticated = true;

        // count remote searches if this was part of a p2p search
        if (mmsp.getMap().containsKey("partitions")) {
            final int partitions = mmsp.getInt("partitions", 30);
            sb.searchQueriesGlobal += 1.0f / partitions; // increase query counter
        }

        // get the ranking profile id
        int profileNr = mmsp.getInt("profileNr", 0);

        // rename post fields according to result style
        String querystring = "";
        if (!mmsp.getMap().containsKey(CommonParams.Q) && mmsp.getMap().containsKey(CommonParams.QUERY)) {
            querystring = mmsp.get(CommonParams.QUERY, "");
            mmsp.getMap().remove(CommonParams.QUERY);
            QueryModifier modifier = new QueryModifier(0);
            querystring = modifier.parse(querystring);
            modifier.apply(mmsp);
            QueryGoal qg = new QueryGoal(querystring);
            StringBuilder solrQ = qg.collectionTextQuery();
            mmsp.getMap().put(CommonParams.Q, new String[] { solrQ.toString() }); // sru patch
        }
        String q = mmsp.get(CommonParams.Q, "");
        if (querystring.length() == 0)
            querystring = q;
        if (!mmsp.getMap().containsKey(CommonParams.START)) {
            int startRecord = mmsp.getFieldInt("startRecord", null, 0);
            mmsp.getMap().remove("startRecord");
            mmsp.getMap().put(CommonParams.START, new String[] { Integer.toString(startRecord) }); // sru patch
        }
        if (!mmsp.getMap().containsKey(CommonParams.ROWS)) {
            int maximumRecords = mmsp.getFieldInt("maximumRecords", null, 10);
            mmsp.getMap().remove("maximumRecords");
            mmsp.getMap().put(CommonParams.ROWS, new String[] { Integer.toString(maximumRecords) }); // sru patch
        }
        mmsp.getMap().put(CommonParams.ROWS, new String[] { Integer
                .toString(Math.min(mmsp.getInt(CommonParams.ROWS, 10), (authenticated) ? 100000000 : 100)) });

        // set ranking according to profile number if ranking attributes are not given in the request
        Ranking ranking = sb.index.fulltext().getDefaultConfiguration().getRanking(profileNr);
        if (!mmsp.getMap().containsKey(CommonParams.SORT) && !mmsp.getMap().containsKey(DisMaxParams.BQ)
                && !mmsp.getMap().containsKey(DisMaxParams.BF) && !mmsp.getMap().containsKey("boost")) {
            if (!mmsp.getMap().containsKey("defType"))
                mmsp.getMap().put("defType", new String[] { "edismax" });
            String fq = ranking.getFilterQuery();
            String bq = ranking.getBoostQuery();
            String bf = ranking.getBoostFunction();
            if (fq.length() > 0)
                mmsp.getMap().put(CommonParams.FQ, new String[] { fq });
            if (bq.length() > 0)
                mmsp.getMap().put(DisMaxParams.BQ, new String[] { bq });
            if (bf.length() > 0)
                mmsp.getMap().put("boost", new String[] { bf }); // a boost function extension, see http://wiki.apache.org/solr/ExtendedDisMax#bf_.28Boost_Function.2C_additive.29
        }

        // get a response writer for the result
        String wt = mmsp.get(CommonParams.WT, "xml"); // maybe use /solr/select?q=*:*&start=0&rows=10&wt=exml
        QueryResponseWriter responseWriter = RESPONSE_WRITER.get(wt);
        if (responseWriter == null)
            throw new ServletException("no response writer");
        if (responseWriter instanceof OpensearchResponseWriter) {
            // set the title every time, it is possible that it has changed
            final String promoteSearchPageGreeting = (sb
                    .getConfigBool(SwitchboardConstants.GREETING_NETWORK_NAME, false))
                            ? sb.getConfig("network.unit.description", "")
                            : sb.getConfig(SwitchboardConstants.GREETING, "");
            ((OpensearchResponseWriter) responseWriter).setTitle(promoteSearchPageGreeting);
        }

        // if this is a call to YaCys special search formats, enhance the query with field assignments
        if ((responseWriter instanceof YJsonResponseWriter
                || responseWriter instanceof OpensearchResponseWriter)
                && "true".equals(mmsp.get("hl", "true"))) {
            // add options for snippet generation
            if (!mmsp.getMap().containsKey("hl.q"))
                mmsp.getMap().put("hl.q", new String[] { q });
            if (!mmsp.getMap().containsKey("hl.fl"))
                mmsp.getMap().put("hl.fl",
                        new String[] { CollectionSchema.description_txt + ","
                                + CollectionSchema.h4_txt.getSolrFieldName() + ","
                                + CollectionSchema.h3_txt.getSolrFieldName() + ","
                                + CollectionSchema.h2_txt.getSolrFieldName() + ","
                                + CollectionSchema.h1_txt.getSolrFieldName() + ","
                                + CollectionSchema.text_t.getSolrFieldName() });
            if (!mmsp.getMap().containsKey("hl.alternateField"))
                mmsp.getMap().put("hl.alternateField",
                        new String[] { CollectionSchema.description_txt.getSolrFieldName() });
            if (!mmsp.getMap().containsKey("hl.simple.pre"))
                mmsp.getMap().put("hl.simple.pre", new String[] { "<b>" });
            if (!mmsp.getMap().containsKey("hl.simple.post"))
                mmsp.getMap().put("hl.simple.post", new String[] { "</b>" });
            if (!mmsp.getMap().containsKey("hl.fragsize"))
                mmsp.getMap().put("hl.fragsize",
                        new String[] { Integer.toString(SearchEvent.SNIPPET_MAX_LENGTH) });
        }

        // get the embedded connector
        String requestURI = hrequest.getRequestURI();
        boolean defaultConnector = (requestURI.startsWith("/solr/" + WebgraphSchema.CORE_NAME)) ? false
                : requestURI.startsWith("/solr/" + CollectionSchema.CORE_NAME)
                        || mmsp.get("core", CollectionSchema.CORE_NAME).equals(CollectionSchema.CORE_NAME);
        mmsp.getMap().remove("core");
        SolrConnector connector = defaultConnector ? sb.index.fulltext().getDefaultEmbeddedConnector()
                : sb.index.fulltext().getEmbeddedConnector(WebgraphSchema.CORE_NAME);
        if (connector == null) {
            connector = defaultConnector ? sb.index.fulltext().getDefaultConnector()
                    : sb.index.fulltext().getConnectorForRead(WebgraphSchema.CORE_NAME);
        }
        if (connector == null)
            throw new ServletException("no core");

        // add default queryfield parameter according to local ranking config (or defaultfield)
        if (ranking != null) { // ranking normally never null
            final String qf = ranking.getQueryFields();
            if (qf.length() > 4) { // make sure qf has content (else use df)
                addParam(DisMaxParams.QF, qf, mmsp.getMap()); // add QF that we set to be best suited for our index
                // TODO: if every peer applies a decent QF itself, this can be reverted to getMap().put()
            } else {
                mmsp.getMap().put(CommonParams.DF, new String[] { CollectionSchema.text_t.getSolrFieldName() });
            }
        } else {
            mmsp.getMap().put(CommonParams.DF, new String[] { CollectionSchema.text_t.getSolrFieldName() });
        }

        // do the solr request, generate facets if we use a special YaCy format
        final SolrQueryResponse rsp;
        if (connector instanceof EmbeddedSolrConnector) {
            req = ((EmbeddedSolrConnector) connector).request(mmsp);
            rsp = ((EmbeddedSolrConnector) connector).query(req);

            // prepare response
            hresponse.setHeader("Cache-Control", "no-cache, no-store");
            HttpCacheHeaderUtil.checkHttpCachingVeto(rsp, hresponse, reqMethod);

            // check error
            if (rsp.getException() != null) {
                AccessTracker.addToDump(querystring, "0", new Date());
                sendError(hresponse, rsp.getException());
                return;
            }

            NamedList<?> values = rsp.getValues();
            DocList r = ((ResultContext) values.get("response")).docs;
            int numFound = r.matches();
            AccessTracker.addToDump(querystring, Integer.toString(numFound), new Date());

            // write response header
            final String contentType = responseWriter.getContentType(req, rsp);
            if (null != contentType)
                response.setContentType(contentType);

            if (Method.HEAD == reqMethod) {
                return;
            }

            // write response body
            if (responseWriter instanceof BinaryResponseWriter) {
                ((BinaryResponseWriter) responseWriter).write(response.getOutputStream(), req, rsp);
            } else {
                out = new FastWriter(new OutputStreamWriter(response.getOutputStream(), UTF8.charset));
                responseWriter.write(out, req, rsp);
                out.flush();
            }
        } else {
            // write a 'faked' response using a call to the backend
            SolrDocumentList sdl = connector.getDocumentListByQuery(mmsp.getMap().get(CommonParams.Q)[0],
                    mmsp.getMap().get(CommonParams.SORT) == null ? null
                            : mmsp.getMap().get(CommonParams.SORT)[0],
                    Integer.parseInt(mmsp.getMap().get(CommonParams.START)[0]),
                    Integer.parseInt(mmsp.getMap().get(CommonParams.ROWS)[0]),
                    mmsp.getMap().get(CommonParams.FL));
            OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
            EnhancedXMLResponseWriter.write(osw, req, sdl);
            osw.close();
        }
    } catch (final Throwable ex) {
        sendError(hresponse, ex);
    } finally {
        if (req != null) {
            req.close();
        }
        SolrRequestInfo.clearRequestInfo();
        if (out != null)
            try {
                out.close();
            } catch (final IOException e1) {
            }
    }
}

From source file:NomusSolrPlugins.NomusDismaxQParserPlugin.java

License:Apache License

public void addDebugInfo(NamedList<Object> debugInfo) {
    super.addDebugInfo(debugInfo);
    debugInfo.add("altquerystring", altUserQuery);
    if (null != boostQueries) {
        debugInfo.add("boost_queries", boostParams);
        debugInfo.add("parsed_boost_queries", QueryParsing.toString(boostQueries, getReq().getSchema()));
    }//ww w  . j  av a  2s .  co m
    debugInfo.add("boostfuncs", getReq().getParams().getParams(DisMaxParams.BF));
}

From source file:org.alfresco.solr.component.spellcheck.AlfrescoSpellCheckCollator.java

License:Open Source License

public List<AlfrescoSpellCheckCollation> collate(SpellingResult result, String originalQuery,
        ResponseBuilder ultimateResponse) {
    List<AlfrescoSpellCheckCollation> collations = new ArrayList<>();

    QueryComponent queryComponent = null;
    if (ultimateResponse.components != null) {
        for (SearchComponent sc : ultimateResponse.components) {
            if (sc instanceof QueryComponent) {
                queryComponent = (QueryComponent) sc;
                break;
            }/*from   ww  w . j  av  a2s  .  c om*/
        }
    }

    boolean verifyCandidateWithQuery = true;
    int maxTries = maxCollationTries;
    int maxNumberToIterate = maxTries;
    if (maxTries < 1) {
        maxTries = 1;
        maxNumberToIterate = maxCollations;
        verifyCandidateWithQuery = false;
    }
    if (queryComponent == null && verifyCandidateWithQuery) {
        LOG.info(
                "Could not find an instance of QueryComponent. Disabling collation verification against the index.");
        maxTries = 1;
        verifyCandidateWithQuery = false;
    }
    docCollectionLimit = docCollectionLimit > 0 ? docCollectionLimit : 0;
    int maxDocId = -1;
    if (verifyCandidateWithQuery && docCollectionLimit > 0) {
        IndexReader reader = ultimateResponse.req.getSearcher().getIndexReader();
        maxDocId = reader.maxDoc();
    }

    JSONObject alfrescoJSON = (JSONObject) ultimateResponse.req.getContext().get(AbstractQParser.ALFRESCO_JSON);
    String originalAftsQuery = alfrescoJSON != null ? alfrescoJSON.getString("query")
            : ultimateResponse.getQueryString();

    int tryNo = 0;
    int collNo = 0;
    PossibilityIterator possibilityIter = new PossibilityIterator(result.getSuggestions(), maxNumberToIterate,
            maxCollationEvaluations, suggestionsMayOverlap);
    while (tryNo < maxTries && collNo < maxCollations && possibilityIter.hasNext()) {
        PossibilityIterator.RankedSpellPossibility possibility = possibilityIter.next();
        String collationQueryStr = getCollation(originalQuery, possibility.corrections);
        int hits = 0;
        String aftsQuery = null;

        if (verifyCandidateWithQuery) {
            tryNo++;
            SolrQueryRequest req = ultimateResponse.req;
            SolrParams origParams = req.getParams();
            ModifiableSolrParams params = new ModifiableSolrParams(origParams);
            Iterator<String> origParamIterator = origParams.getParameterNamesIterator();
            int pl = SpellingParams.SPELLCHECK_COLLATE_PARAM_OVERRIDE.length();
            while (origParamIterator.hasNext()) {
                String origParamName = origParamIterator.next();
                if (origParamName.startsWith(SpellingParams.SPELLCHECK_COLLATE_PARAM_OVERRIDE)
                        && origParamName.length() > pl) {
                    String[] val = origParams.getParams(origParamName);
                    if (val.length == 1 && val[0].length() == 0) {
                        params.set(origParamName.substring(pl), (String[]) null);
                    } else {
                        params.set(origParamName.substring(pl), val);
                    }
                }
            }
            // we don't set the 'q' param, as we'll pass the query via JSON.
            // params.set(CommonParams.Q, collationQueryStr);
            params.remove(CommonParams.START);
            params.set(CommonParams.ROWS, "" + docCollectionLimit);
            // we don't want any stored fields
            params.set(CommonParams.FL, "id");
            // we'll sort by doc id to ensure no scoring is done.
            params.set(CommonParams.SORT, "_docid_ asc");
            // If a dismax query, don't add unnecessary clauses for scoring
            params.remove(DisMaxParams.TIE);
            params.remove(DisMaxParams.PF);
            params.remove(DisMaxParams.PF2);
            params.remove(DisMaxParams.PF3);
            params.remove(DisMaxParams.BQ);
            params.remove(DisMaxParams.BF);
            // Collate testing does not support Grouping (see SOLR-2577)
            params.remove(GroupParams.GROUP);

            boolean useQStr = true;

            if (alfrescoJSON != null) {
                try {
                    aftsQuery = originalAftsQuery.replaceAll(Pattern.quote(originalQuery),
                            Matcher.quoteReplacement(collationQueryStr));
                    alfrescoJSON.put("query", aftsQuery);
                    req.getContext().put(AbstractQParser.ALFRESCO_JSON, alfrescoJSON);
                    useQStr = false;
                } catch (JSONException e) {
                    LOG.warn("Exception trying to get/set the query from/to ALFRESCO_JSON.]" + e);
                }
            } else {
                aftsQuery = collationQueryStr;
            }
            req.setParams(params);
            // creating a request here... make sure to close it!
            ResponseBuilder checkResponse = new ResponseBuilder(req, new SolrQueryResponse(),
                    Arrays.<SearchComponent>asList(queryComponent));
            checkResponse.setQparser(ultimateResponse.getQparser());
            checkResponse.setFilters(ultimateResponse.getFilters());
            checkResponse.components = Arrays.<SearchComponent>asList(queryComponent);
            if (useQStr) {
                checkResponse.setQueryString(collationQueryStr);
            }
            try {
                queryComponent.prepare(checkResponse);
                if (docCollectionLimit > 0) {
                    int f = checkResponse.getFieldFlags();
                    checkResponse.setFieldFlags(f |= SolrIndexSearcher.TERMINATE_EARLY);
                }
                queryComponent.process(checkResponse);
                hits = (Integer) checkResponse.rsp.getToLog().get("hits");
            } catch (EarlyTerminatingCollectorException etce) {
                assert (docCollectionLimit > 0);
                assert 0 < etce.getNumberScanned();
                assert 0 < etce.getNumberCollected();

                if (etce.getNumberScanned() == maxDocId) {
                    hits = etce.getNumberCollected();
                } else {
                    hits = (int) (((float) (maxDocId * etce.getNumberCollected()))
                            / (float) etce.getNumberScanned());
                }
            } catch (Exception e) {
                LOG.warn(
                        "Exception trying to re-query to check if a spell check possibility would return any hits."
                                + e);
            } finally {
                checkResponse.req.close();
            }
        }
        if (hits > 0 || !verifyCandidateWithQuery) {
            collNo++;
            AlfrescoSpellCheckCollation collation = new AlfrescoSpellCheckCollation();
            collation.setCollationQuery(aftsQuery);
            collation.setCollationQueryString(collationQueryStr);
            collation.setHits(hits);
            collation.setInternalRank(
                    suggestionsMayOverlap ? ((possibility.rank * 1000) + possibility.index) : possibility.rank);

            NamedList<String> misspellingsAndCorrections = new NamedList<>();
            for (SpellCheckCorrection corr : possibility.corrections) {
                misspellingsAndCorrections.add(corr.getOriginal().toString(), corr.getCorrection());
            }
            collation.setMisspellingsAndCorrections(misspellingsAndCorrections);
            collations.add(collation);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Collation: " + aftsQuery
                    + (verifyCandidateWithQuery ? (" will return " + hits + " hits.") : ""));
        }
    }
    return collations;
}