Example usage for org.apache.solr.common.params CommonParams FL

List of usage examples for org.apache.solr.common.params CommonParams FL

Introduction

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

Prototype

String FL

To view the source code for org.apache.solr.common.params CommonParams FL.

Click Source Link

Document

query and init param for field list

Usage

From source file:io.redlink.solr.client.solrj.tag.TagParams.java

License:LGPL

/**
 * Setter for the list of fields returned for {@link SolrDocument}s
 * referenced by Tags/* ww  w.  ja  va  2s.  c  o m*/
 * @param fields the fields
 * @return this
 */
public TagParams setFields(String... fields) {
    if (fields == null || fields.length == 0) {
        this.remove(CommonParams.FL);
        return this;
    }
    StringBuilder sb = new StringBuilder();
    sb.append(fields[0]);
    for (int i = 1; i < fields.length; i++) {
        sb.append(',');
        sb.append(fields[i]);
    }
    this.set(CommonParams.FL, sb.toString());
    return this;
}

From source file:io.redlink.solr.client.solrj.tag.TagParams.java

License:LGPL

/**
 * Adds a field to be returned for {@link SolrDocument}s referenced by Tags
 * @param field the fields name/*from ww  w .j a  v a 2  s  .  co  m*/
 * @return this
 */
public TagParams addField(String field) {
    return addValueToParam(CommonParams.FL, field);
}

From source file:io.redlink.solr.client.solrj.tag.TagParams.java

License:LGPL

/**
 * Getter for the fields included for {@link SolrDocument} referenced by
 * Tags/*w w  w .j av a 2 s. c  om*/
 * @return the field named separated by comma
 */
public String getFields() {
    String fields = this.get(CommonParams.FL);
    if (fields != null && fields.equals("score")) {
        fields = "*, score";
    }
    return fields;
}

From source file:net.yacy.cora.federate.solr.connector.EmbeddedSolrConnector.java

License:Open Source License

/**
 * the usage of getResponseByParams is disencouraged for the embedded Solr connector. Please use request(SolrParams) instead.
 * Reason: Solr makes a very complex folding/unfolding including data compression for SolrQueryResponses.
 *//* w ww . ja v  a2  s . c o  m*/
@Override
public QueryResponse getResponseByParams(ModifiableSolrParams params) throws IOException {
    if (this.server == null)
        throw new IOException("server disconnected");
    // during the solr query we set the thread name to the query string to get more debugging info in thread dumps
    String q = params.get(CommonParams.Q);
    String fl = params.get(CommonParams.FL);
    String[] fq = params.getParams(CommonParams.FQ);
    String threadname = Thread.currentThread().getName();
    if (q != null) {
        StringBuilder fqa = new StringBuilder();
        if (fq != null)
            for (String f : fq)
                fqa.append("fq=").append(f).append(' ');
        Thread.currentThread().setName("solr query: q = " + q + (fq == null ? "" : ", " + fqa.toString())
                + (fl == null ? "" : ", fl=" + fl));
        //System.out.println("solr query: q = " + q + (fq == null ? "" : ", " + fqa.toString()) + (fl == null ? "" : ", fl=" + fl));
    }
    QueryResponse rsp;
    try {
        rsp = this.server.query(params);
        if (q != null)
            Thread.currentThread().setName(threadname);
        if (rsp != null)
            if (log.isFine())
                log.fine(rsp.getResults().getNumFound() + " results for q=" + q);
        return rsp;
    } catch (final SolrServerException e) {
        throw new IOException(e);
    } catch (final Throwable e) {
        throw new IOException("Error executing query", e);
    }
}

From source file:net.yacy.cora.federate.solr.connector.SolrServerConnector.java

License:Open Source License

/**
 * get the solr document list from a query response
 * This differs from getResponseByParams in such a way that it does only create the fields of the response but
 * never search snippets and there are also no facets generated.
 * @param params/*from w  w w. ja  v  a2 s . c  om*/
 * @return
 * @throws IOException
 * @throws SolrException
 */
@Override
public SolrDocumentList getDocumentListByParams(ModifiableSolrParams params) throws IOException {
    if (this.server == null)
        throw new IOException("server disconnected");
    // during the solr query we set the thread name to the query string to get more debugging info in thread dumps
    String q = params.get(CommonParams.Q);
    String fq = params.get(CommonParams.FQ);
    String sort = params.get(CommonParams.SORT);
    String fl = params.get(CommonParams.FL);
    String threadname = Thread.currentThread().getName();
    QueryResponse rsp;
    int retry = 0;
    Throwable error = null;
    while (retry++ < 10) {
        try {
            if (q != null)
                Thread.currentThread().setName("solr query: q = " + q + (fq == null ? "" : ", fq = " + fq)
                        + (sort == null ? "" : ", sort = " + sort) + "; retry = " + retry + "; fl = " + fl); // for debugging in Threaddump
            rsp = this.server.query(params);
            if (q != null)
                Thread.currentThread().setName(threadname);
            if (rsp != null)
                if (log.isFine())
                    log.fine(rsp.getResults().getNumFound() + " results for q=" + q);
            return rsp.getResults();
        } catch (final SolrServerException e) {
            error = e;
        } catch (final Throwable e) {
            error = e;
            clearCaches(); // prevent further OOM if this was caused by OOM
        }
        ConcurrentLog.severe("SolrServerConnector", "Failed to query remote Solr: " + error.getMessage()
                + ", query:" + q + (fq == null ? "" : ", fq = " + fq));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
    }
    throw new IOException("Error executing query", error);
}

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

License:Open Source License

/**
 * from here copy of htroot/gsa/gsasearchresult.java
 * with modification to use HttpServletRequest instead of (yacy) RequestHeader
 *//*from   www  .j a v  a2  s. c  om*/

public static void respond(final HttpServletRequest header, final Switchboard sb, final OutputStream out) {

    // remember the peer contact for peer statistics
    String clientip = header.getHeader(HeaderFramework.CONNECTION_PROP_CLIENTIP);
    if (clientip == null)
        clientip = "<unknown>"; // read an artificial header addendum
    String userAgent = header.getHeader(HeaderFramework.USER_AGENT);
    if (userAgent == null)
        userAgent = "<unknown>";
    sb.peers.peerActions.setUserAgent(clientip, userAgent);

    // --- handled by Servlet securityHandler
    // check if user is allowed to search (can be switched in /ConfigPortal.html)
    boolean authenticated = header.isUserInRole(UserDB.AccessRight.ADMIN_RIGHT.toString()); //sb.adminAuthenticated(header) >= 2;
    // final boolean searchAllowed = authenticated || sb.getConfigBool(SwitchboardConstants.PUBLIC_SEARCHPAGE, true);
    // if (!searchAllowed) return null;

    // create post
    serverObjects post = new serverObjects();
    post.put(CommonParams.Q, "");
    post.put("num", "0");
    // convert servletrequest parameter to old style serverObjects map
    Map<String, String[]> map = header.getParameterMap();
    Iterator<Map.Entry<String, String[]>> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String[]> param = it.next();
        post.put(param.getKey(), param.getValue()); // hint: post.put uses String[] for String value anyways
    }

    ConcurrentLog.info("GSA Query", post.toString());
    sb.intermissionAllThreads(3000); // tell all threads to do nothing for a specific time

    // rename post fields according to result style
    //post.put(CommonParams.Q, post.remove("q")); // same as solr
    //post.put(CommonParams.START, post.remove("start")); // same as solr
    //post.put(, post.remove("client"));//required, example: myfrontend
    //post.put(, post.remove("output"));//required, example: xml,xml_no_dtd
    String originalQuery = post.get(CommonParams.Q, "");
    post.put("originalQuery", originalQuery);

    // get a solr query string
    QueryGoal qg = new QueryGoal(originalQuery);
    List<String> solrFQ = qg.collectionTextFilterQuery(false);
    StringBuilder solrQ = qg.collectionTextQuery();
    post.put("defType", "edismax");
    for (String fq : solrFQ)
        post.add(CommonParams.FQ, fq);
    post.put(CommonParams.Q, solrQ.toString());
    post.put(CommonParams.ROWS, post.remove("num"));
    post.put(CommonParams.ROWS,
            Math.min(post.getInt(CommonParams.ROWS, 10), (authenticated) ? 100000000 : 100));

    // set ranking
    final Ranking ranking = sb.index.fulltext().getDefaultConfiguration().getRanking(0);
    final String qf = ranking.getQueryFields();
    if (!qf.isEmpty())
        post.put(DisMaxParams.QF, qf);
    if (post.containsKey(CommonParams.SORT)) {
        // if a gsa-style sort attribute is given, use this to set the solr sort attribute
        GSAResponseWriter.Sort sort = new GSAResponseWriter.Sort(post.get(CommonParams.SORT, ""));
        String sorts = sort.toSolr();
        if (sorts == null) {
            post.remove(CommonParams.SORT);
        } else {
            post.put(CommonParams.SORT, sorts);
        }
    } else {
        // if no such sort attribute is given, use the ranking as configured for YaCy
        String fq = ranking.getFilterQuery();
        String bq = ranking.getBoostQuery();
        String bf = ranking.getBoostFunction();
        if (fq.length() > 0)
            post.put(CommonParams.FQ, fq);
        if (bq.length() > 0)
            post.put(DisMaxParams.BQ, bq);
        if (bf.length() > 0)
            post.put("boost", bf); // a boost function extension, see http://wiki.apache.org/solr/ExtendedDisMax#bf_.28Boost_Function.2C_additive.29
    }
    String daterange[] = post.remove("daterange");
    if (daterange != null) {
        String origfq = post.get(CommonParams.FQ);
        String datefq = "";
        for (String dr : daterange) {
            String from_to[] = dr.endsWith("..") ? new String[] { dr.substring(0, dr.length() - 2), "" }
                    : dr.startsWith("..") ? new String[] { "", dr.substring(2) } : dr.split("\\.\\.");
            if (from_to.length != 2)
                continue;
            Date from = HeaderFramework.parseGSAFS(from_to[0]);
            if (from == null)
                from = new Date(0);
            Date to = HeaderFramework.parseGSAFS(from_to[1]);
            if (to == null)
                to = new Date();
            to.setTime(to.getTime() + 24L * 60L * 60L * 1000L); // we add a day because the day is inclusive
            String z = CollectionSchema.last_modified.getSolrFieldName() + ":["
                    + ISO8601Formatter.FORMATTER.format(from) + " TO " + ISO8601Formatter.FORMATTER.format(to)
                    + "]";
            datefq = datefq.length() == 0 ? z : " OR " + z;
        }
        if (datefq.length() > 0)
            post.put(CommonParams.FQ,
                    origfq == null || origfq.length() == 0 ? datefq : "(" + origfq + ") AND (" + datefq + ")");
    }
    post.put(CommonParams.FL,
            CollectionSchema.content_type.getSolrFieldName() + ',' + CollectionSchema.id.getSolrFieldName()
                    + ',' + CollectionSchema.sku.getSolrFieldName() + ','
                    + CollectionSchema.title.getSolrFieldName() + ','
                    + CollectionSchema.description_txt.getSolrFieldName() + ','
                    + CollectionSchema.load_date_dt.getSolrFieldName() + ','
                    + CollectionSchema.last_modified.getSolrFieldName() + ','
                    + CollectionSchema.size_i.getSolrFieldName());
    post.put("hl", "true");
    post.put("hl.q", originalQuery);
    post.put("hl.fl", CollectionSchema.description_txt + "," + CollectionSchema.h4_txt.getSolrFieldName() + ","
            + CollectionSchema.h3_txt.getSolrFieldName() + "," + CollectionSchema.h2_txt.getSolrFieldName()
            + "," + CollectionSchema.h1_txt.getSolrFieldName() + ","
            + CollectionSchema.text_t.getSolrFieldName());
    post.put("hl.alternateField", CollectionSchema.description_txt.getSolrFieldName());
    post.put("hl.simple.pre", "<b>");
    post.put("hl.simple.post", "</b>");
    post.put("hl.fragsize", Integer.toString(SearchEvent.SNIPPET_MAX_LENGTH));

    //String[] access = post.remove("access");
    //String[] entqr = post.remove("entqr");

    // add sites operator
    String[] site = post.remove("site"); // example: col1|col2
    if (site != null && site[0].length() > 0) {
        String origfq = post.get(CommonParams.FQ);
        String sitefq = QueryModifier.parseCollectionExpression(site[0]);
        post.put(CommonParams.FQ,
                origfq == null || origfq.length() == 0 ? sitefq : "(" + origfq + ") AND (" + sitefq + ")");
    }

    // get the embedded connector
    EmbeddedSolrConnector connector = sb.index.fulltext().getDefaultEmbeddedConnector();
    if (connector == null)
        return;

    // do the solr request
    SolrQueryRequest req = connector.request(post.toSolrParams(null));
    SolrQueryResponse response = null;
    Exception e = null;
    try {
        response = connector.query(req);
    } catch (final SolrException ee) {
        e = ee;
    }
    if (response != null)
        e = response.getException();
    if (e != null) {
        ConcurrentLog.logException(e);
        if (req != null)
            req.close();
        SolrRequestInfo.clearRequestInfo();
        return;
    }

    // set some context for the writer
    /*
    Map<Object,Object> context = req.getContext();
    context.put("ip", header.get("CLIENTIP", ""));
    context.put("client", "vsm_frontent");
    context.put("sort", sort.sort);
    context.put("site", site == null ? "" : site);
    context.put("access", access == null ? "p" : access[0]);
    context.put("entqr", entqr == null ? "3" : entqr[0]);
    */

    // write the result directly to the output stream
    Writer ow = new FastWriter(new OutputStreamWriter(out, UTF8.charset));
    try {
        responseWriter.write(ow, req, response);
        ow.flush();
    } catch (final IOException e1) {
    } finally {
        req.close();
        SolrRequestInfo.clearRequestInfo();
        try {
            ow.close();
        } catch (final IOException e1) {
        }
    }

    // log result
    Object rv = response.getValues().get("response");
    int matches = 0;
    if (rv != null && rv instanceof ResultContext) {
        matches = ((ResultContext) rv).docs.matches();
    } else if (rv != null && rv instanceof SolrDocumentList) {
        matches = (int) ((SolrDocumentList) rv).getNumFound();
    }
    AccessTracker.addToDump(originalQuery, Integer.toString(matches));
    ConcurrentLog.info("GSA Query", "results: " + matches + ", for query:" + post.toString());
}

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;//from ww  w  .j a  v  a  2 s  .co  m

    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:opennlp.tools.similarity.apps.solr.IterativeSearchRequestHandler.java

License:Apache License

private void doSearch1(SolrDocumentList results, SolrIndexSearcher searcher, String q, Filter filter, int ndocs,
        SolrQueryRequest req, Map<String, SchemaField> fields, Set<Integer> alreadyFound) throws IOException {

    // build custom query and extra fields
    Query query = null; //buildCustomQuery1(q);
    Map<String, Object> extraFields = new HashMap<String, Object>();
    extraFields.put("search_type", "search1");
    boolean includeScore = req.getParams().get(CommonParams.FL).contains("score");

    int maxDocsPerSearcherType = 0;
    float maprelScoreCutoff = 2.0f;
    append(results, searcher.search(query, filter, maxDocsPerSearcherType).scoreDocs, alreadyFound, fields,
            extraFields, maprelScoreCutoff, searcher.getIndexReader(), includeScore);
}

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;
            }/*  w  w w.j a v a 2  s  .co  m*/
        }
    }

    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;
}

From source file:org.alfresco.solr.SolrInformationServer.java

License:Open Source License

@Override
public long getIndexCap() {
    try (SolrQueryRequest request = this.newSolrQueryRequest()) {
        ModifiableSolrParams params = new ModifiableSolrParams(request.getParams())
                .set(CommonParams.Q, FIELD_SOLR4_ID + ":" + INDEX_CAP_ID).set(CommonParams.ROWS, 1)
                .set(CommonParams.FL, FIELD_DBID);

        SolrDocumentList docs = cloud.getSolrDocumentList(nativeRequestHandler, request, params);

        return docs.stream().findFirst().map(doc -> getFieldValueLong(doc, FIELD_DBID)).map(Math::abs)
                .orElse(-1L);/*  ww  w  . ja v  a2 s  .c o  m*/
    }
}