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

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

Introduction

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

Prototype

String START

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

Click Source Link

Document

zero based offset of matching documents to retrieve

Usage

From source file:com.doculibre.constellio.opensearch.OpenSearchSolrServer.java

License:Open Source License

@Override
public NamedList<Object> request(SolrRequest request) throws SolrServerException, IOException {
    SolrParams params = request.getParams();
    if (params == null) {
        params = new ModifiableSolrParams();
    }//from w w w  . j a v a  2 s  . co m

    String openSearchURL = params.get("openSearchURL");
    if (openSearchURL == null) {
        throw new SolrServerException("openSearchURL param is missing");
    }
    String query = params.get(CommonParams.Q);
    int start = params.getInt(CommonParams.START, 0);
    int hitsPerPage = params.getInt(CommonParams.ROWS, 10);
    String lang = params.get("lang");

    Map<String, String> paramsMap = new HashMap<String, String>();
    if (SimpleSearch.SEARCH_ALL.equals(query)) {
        query = "url:http";
    }
    paramsMap.put("query", query);
    if (StringUtils.isNotBlank(lang)) {
        paramsMap.put("lang", "" + lang);
    }
    paramsMap.put("start", "" + start);
    paramsMap.put("hitsPerPage", "" + hitsPerPage);
    // FIXME
    paramsMap.put("hitsPerDup", "" + Integer.MAX_VALUE);
    Element rootElement = sendGet(openSearchURL, paramsMap);

    SolrDocumentList solrDocumentList = parse(rootElement);
    SimpleOrderedMap<Object> result = new SimpleOrderedMap<Object>();
    result.add("response", solrDocumentList);
    return result;
}

From source file:com.doculibre.constellio.opensearch.OpenSearchSolrServer.java

License:Open Source License

public static void main(String[] args) throws Exception {
    SolrDocumentList solrDocumentList;//from   w ww  . j av  a  2 s  . c o  m
    //        
    // InputStream inputXML = OpenSearchSolrServer.class.getResourceAsStream("opensearch_example.xml");
    // SAXReader saxReader = new SAXReader();
    // Document doc = saxReader.read(inputXML);
    // IOUtils.closeQuietly(inputXML);
    //
    // System.out.println("Mock request");
    // solrDocumentList = parse(doc.getRootElement());
    // printResults(solrDocumentList);

    System.out.println("Real request");
    OpenSearchSolrServer solrServer = new OpenSearchSolrServer();
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add("openSearchURL", "http://recherched.gouv.qc.ca/internet/opensearch");
    params.add(CommonParams.Q, "doculibre");
    params.add(CommonParams.START, "5");
    params.add(CommonParams.ROWS, "10");
    params.add("lang", "en");
    NamedList<Object> results = solrServer.request(new QueryRequest(params));
    solrDocumentList = (SolrDocumentList) results.get("response");
    printResults(solrDocumentList);

    QueryResponse queryResponse = solrServer.query(params);
    solrDocumentList = queryResponse.getResults();
    printResults(solrDocumentList);
}

From source file:com.frank.search.common.PagerComponent.java

License:GNU General Public License

@Override
@SuppressWarnings("unchecked")
public void process(ResponseBuilder rb) throws IOException {
    /* get request params */
    SolrParams par = rb.req.getParams();
    int rows = par.getInt(CommonParams.ROWS, 0);
    int start = par.getInt(CommonParams.START, 0);
    int pages = par.getInt(PARAM_PAGER, 0);
    int pages_pre = par.getInt(PARAM_PAGER_PRE, 2);

    /* neet to work ? */
    if (pages == 0 || rows == 0)
        return;//ww  w  .  j  a va 2 s.  co m

    /* pager list */
    NamedList lst = new SimpleOrderedMap<Object>();
    NamedList lst2 = new SimpleOrderedMap<Object>();

    /* paging pages */
    int doc_count = rb.getResults().docSet.size();
    int page_count = doc_count / rows;
    int page_actual = start / rows;
    int page_pre = pages_pre;
    int page_post = pages - page_pre - 1;

    /* page range */
    if (page_actual - page_pre < 0) {
        page_post += -(page_actual - page_pre);
        page_pre -= -(page_actual - page_pre);
    } else if (page_actual + page_post > page_count) {
        page_post = pages - page_pre;
        page_pre = page_actual + pages - page_count;
    }

    /* sanity */
    if (page_pre < 0)
        page_pre = 0;
    if (page_post < 0)
        page_post = 0;

    /* next pages list */
    int i = (page_actual - page_pre);
    for (i = (i <= 0 ? 0 : i); i <= page_count && i <= (page_actual + page_post); i++)
        lst2.add(Integer.toString(i + 1), i * rows);
    lst.add("pages", lst2);

    /* navi */
    if (page_actual > 0)
        lst.add("prev", (page_actual - 1) * rows);
    if (page_actual - page_pre > 0)
        lst.add("first", 0);
    if (page_actual < page_count)
        lst.add("next", (page_actual + 1) * rows);
    if (page_actual + page_post < page_count)
        lst.add("last", page_count * rows);
    lst.add("actual", page_actual + 1);
    lst.add("count", page_count);

    /* finish */
    rb.rsp.add("pager", lst);
}

From source file:com.searchbox.solr.CategoryLikeThis.java

License:Apache License

@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    numRequests++;//w  ww .  j  ava  2 s.c  o m
    long startTime = System.currentTimeMillis();
    if (!keystate) {
        LOGGER.error(
                "License key failure, not performing clt query. Please email contact@searchbox.com for more information.");
        return;
    }

    try {
        SolrParams params = req.getParams();
        String senseField = params.get(SenseParams.SENSE_FIELD, SenseParams.DEFAULT_SENSE_FIELD);
        BooleanQuery catfilter = new BooleanQuery();
        // Set field flags
        ReturnFields returnFields = new SolrReturnFields(req);
        rsp.setReturnFields(returnFields);
        int flags = 0;
        if (returnFields.wantsScore()) {
            flags |= SolrIndexSearcher.GET_SCORES;
        }

        String defType = params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE);
        String q = params.get(CommonParams.Q);
        Query query = null;
        SortSpec sortSpec = null;
        List<Query> filters = new LinkedList<Query>();
        List<RealTermFreqVector> prototypetfs = new LinkedList<RealTermFreqVector>();

        try {
            if (q != null) {
                QParser parser = QParser.getParser(q, defType, req);
                query = parser.getQuery();
                sortSpec = parser.getSort(true);
            }

            String[] fqs = req.getParams().getParams(CommonParams.FQ);
            if (fqs != null && fqs.length != 0) {
                for (String fq : fqs) {
                    if (fq != null && fq.trim().length() != 0) {
                        QParser fqp = QParser.getParser(fq, null, req);
                        filters.add(fqp.getQuery());
                    }
                }
            }
        } catch (Exception e) {
            numErrors++;
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
        }

        SolrIndexSearcher searcher = req.getSearcher();
        DocListAndSet cltDocs = null;

        // Parse Required Params
        // This will either have a single Reader or valid query
        Reader reader = null;
        try {
            if (q == null || q.trim().length() < 1) {
                Iterable<ContentStream> streams = req.getContentStreams();
                if (streams != null) {
                    Iterator<ContentStream> iter = streams.iterator();
                    if (iter.hasNext()) {
                        reader = iter.next().getReader();
                    }
                    if (iter.hasNext()) {
                        numErrors++;
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                                "SenseLikeThis does not support multiple ContentStreams");
                    }
                }
            }

            int start = params.getInt(CommonParams.START, 0);
            int rows = params.getInt(CommonParams.ROWS, 10);

            // Find documents SenseLikeThis - either with a reader or a query
            // --------------------------------------------------------------------------------
            if (reader != null) {
                numErrors++;
                throw new RuntimeException("SLT based on a reader is not yet implemented");
            } else if (q != null) {

                LOGGER.debug("Query for category:\t" + query);
                DocList match = searcher.getDocList(query, null, null, 0, 10, flags); // get first 10
                if (match.size() == 0) { // no docs to make prototype!
                    LOGGER.info("No documents found for prototype!");
                    rsp.add("response", new DocListAndSet());
                    return;
                }

                HashMap<String, Float> overallFreqMap = new HashMap<String, Float>();
                // Create the TF of blah blah blah
                DocIterator iterator = match.iterator();
                while (iterator.hasNext()) {
                    // do a MoreLikeThis query for each document in results
                    int id = iterator.nextDoc();
                    LOGGER.trace("Working on doc:\t" + id);
                    RealTermFreqVector rtv = new RealTermFreqVector(id, searcher.getIndexReader(), senseField);
                    for (int zz = 0; zz < rtv.getSize(); zz++) {
                        Float prev = overallFreqMap.get(rtv.getTerms()[zz]);
                        if (prev == null) {
                            prev = 0f;
                        }
                        overallFreqMap.put(rtv.getTerms()[zz], rtv.getFreqs()[zz] + prev);
                    }
                    prototypetfs.add(rtv);
                }

                List<String> sortedKeys = Ordering.natural().onResultOf(Functions.forMap(overallFreqMap))
                        .immutableSortedCopy(overallFreqMap.keySet());
                int keyiter = Math.min(sortedKeys.size() - 1, BooleanQuery.getMaxClauseCount() - 1);
                LOGGER.debug("I have this many terms:\t" + sortedKeys.size());
                LOGGER.debug("And i'm going to use this many:\t" + keyiter);
                for (; keyiter >= 0; keyiter--) {
                    TermQuery tq = new TermQuery(new Term(senseField, sortedKeys.get(keyiter)));
                    catfilter.add(tq, BooleanClause.Occur.SHOULD);
                }

            } else {
                numErrors++;
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                        "CategoryLikeThis requires either a query (?q=) or text to find similar documents.");
            }

            LOGGER.debug("document filter is: \t" + catfilter);
            CategorizationBase model = new CategorizationBase(prototypetfs);
            CategoryQuery clt = CategoryQuery.CategoryQueryForDocument(catfilter, model,
                    searcher.getIndexReader(), senseField);
            DocSet filtered = searcher.getDocSet(filters);
            cltDocs = searcher.getDocListAndSet(clt, filtered, Sort.RELEVANCE, start, rows, flags);
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        if (cltDocs == null) {
            numEmpty++;
            cltDocs = new DocListAndSet(); // avoid NPE
        }
        rsp.add("response", cltDocs.docList);

        // maybe facet the results
        if (params.getBool(FacetParams.FACET, false)) {
            if (cltDocs.docSet == null) {
                rsp.add("facet_counts", null);
            } else {
                SimpleFacets f = new SimpleFacets(req, cltDocs.docSet, params);
                rsp.add("facet_counts", f.getFacetCounts());
            }
        }
    } catch (Exception e) {
        numErrors++;
    } finally {
        totalTime += System.currentTimeMillis() - startTime;
    }

}

From source file:com.searchbox.solr.SenseLikeThisHandler.java

License:Apache License

@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    NamedList<Object> timinginfo = new NamedList<Object>();
    numRequests++;/*from  ww w . ja  va 2 s.  com*/
    long startTime = System.currentTimeMillis();
    long lstartTime = System.currentTimeMillis();
    if (!keystate) {
        LOGGER.error(
                "License key failure, not performing sense query. Please email contact@searchbox.com for more information.");
        return;
    }

    boolean fromcache = false;

    try {
        SolrParams params = req.getParams();
        int start = params.getInt(CommonParams.START, 0);
        int rows = params.getInt(CommonParams.ROWS, 10);

        HashSet<String> toIgnore = (new HashSet<String>());
        toIgnore.add("start");
        toIgnore.add("rows");
        toIgnore.add("fl");
        toIgnore.add("wt");
        toIgnore.add("indent");

        SolrCacheKey key = new SolrCacheKey(params, toIgnore);

        // Set field flags
        ReturnFields returnFields = new SolrReturnFields(req);
        rsp.setReturnFields(returnFields);
        int flags = 0;
        if (returnFields.wantsScore()) {
            flags |= SolrIndexSearcher.GET_SCORES;
        }

        String defType = params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE);
        String q = params.get(CommonParams.Q);
        Query query = null;
        QueryReductionFilter qr = null;
        SortSpec sortSpec = null;
        List<Query> filters = new ArrayList<Query>();

        try {
            if (q != null) {
                QParser parser = QParser.getParser(q, defType, req);
                query = parser.getQuery();
                sortSpec = parser.getSort(true);
            }

            String[] fqs = req.getParams().getParams(CommonParams.FQ);
            if (fqs != null && fqs.length != 0) {
                for (String fq : fqs) {
                    if (fq != null && fq.trim().length() != 0) {
                        QParser fqp = QParser.getParser(fq, null, req);
                        filters.add(fqp.getQuery());
                    }
                }
            }
        } catch (Exception e) {
            numErrors++;
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
        }

        timinginfo.add("Parse Query time", System.currentTimeMillis() - lstartTime);
        LOGGER.debug("Parsed Query Time:\t" + (System.currentTimeMillis() - lstartTime));
        lstartTime = System.currentTimeMillis();

        SolrIndexSearcher searcher = req.getSearcher();
        SchemaField uniqueKeyField = searcher.getSchema().getUniqueKeyField();

        // Parse Required Params
        // This will either have a single Reader or valid query

        // Find documents SenseLikeThis - either with a reader or a query
        // --------------------------------------------------------------------------------
        SenseQuery slt = null;
        if (q == null) {
            numErrors++;
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                    "SenseLikeThis requires either a query (?q=) or text to find similar documents.");

        }
        // Matching options
        boolean includeMatch = params.getBool(MoreLikeThisParams.MATCH_INCLUDE, true);
        int matchOffset = params.getInt(MoreLikeThisParams.MATCH_OFFSET, 0);
        // Find the base match

        DocList match = searcher.getDocList(query, null, null, matchOffset, 1, flags); // only get the first one...
        if (includeMatch) {
            rsp.add("match", match);
        }

        DocIterator iterator = match.iterator();
        if (!iterator.hasNext()) {
            numErrors++;
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                    "SenseLikeThis no document found matching request.");
        }
        int id = iterator.nextDoc();

        timinginfo.add("Find Query Doc", System.currentTimeMillis() - lstartTime);
        LOGGER.debug("Find Query Doc:\t" + (System.currentTimeMillis() - lstartTime));
        lstartTime = System.currentTimeMillis();

        SolrCache sc = searcher.getCache("com.searchbox.sltcache");
        DocListAndSet sltDocs = null;
        if (sc != null) {
            //try to get from cache
            sltDocs = (DocListAndSet) sc.get(key.getSet());
        } else {
            LOGGER.error("com.searchbox.sltcache not defined, can't cache slt queries");
        }

        sltDocs = (DocListAndSet) sc.get(key.getSet());
        if (start + rows > 1000 || sltDocs == null || !params.getBool(CommonParams.CACHE, true)) { //not in cache, need to do search
            BooleanQuery bq = new BooleanQuery();
            Document doc = searcher.getIndexReader().document(id);
            bq.add(new TermQuery(new Term(uniqueKeyField.getName(),
                    uniqueKeyField.getType().storedToIndexed(doc.getField(uniqueKeyField.getName())))),
                    BooleanClause.Occur.MUST_NOT);
            filters.add(bq);

            String[] senseFields = splitList
                    .split(params.get(SenseParams.SENSE_FIELD, SenseParams.DEFAULT_SENSE_FIELD));
            String senseField = (senseFields[0] != null) ? senseFields[0] : SenseParams.DEFAULT_SENSE_FIELD;

            //TODO more intelligent handling of multiple fields , can probably do a boolean junction of multiple sensequeries, but this will be slow
            long maxlength = -1;
            for (String possibleField : senseFields) {
                try {
                    long flength = doc.getField(possibleField).stringValue().length();
                    if (flength > maxlength) {
                        senseField = possibleField;
                        maxlength = flength;
                    }
                } catch (Exception e) {
                    System.out.println("Error: " + e.getMessage());
                }
            }

            LOGGER.debug("Using sense field :\t" + (senseField));

            String CKBid = params.get(SenseParams.SENSE_CKB, SenseParams.SENSE_CKB_DEFAULT);

            RealTermFreqVector rtv = new RealTermFreqVector(id, searcher.getIndexReader(), senseField);
            timinginfo.add("Make real term freq vector", System.currentTimeMillis() - lstartTime);
            lstartTime = System.currentTimeMillis();

            qr = new QueryReductionFilter(rtv, CKBid, searcher, senseField);
            qr.setNumtermstouse(params.getInt(SenseParams.SENSE_QR_NTU, SenseParams.SENSE_QR_NTU_DEFAULT));
            qr.setThreshold(params.getInt(SenseParams.SENSE_QR_THRESH, SenseParams.SENSE_QR_THRESH_DEFAULT));
            qr.setMaxDocSubSet(params.getInt(SenseParams.SENSE_QR_MAXDOC, SenseParams.SENSE_QR_MAXDOC_DEFAULT));
            qr.setMinDocSetSizeForFilter(
                    params.getInt(SenseParams.SENSE_MINDOC4QR, SenseParams.SENSE_MINDOC4QR_DEFAULT));

            numTermsUsed += qr.getNumtermstouse();
            numTermsConsidered += rtv.getSize();

            timinginfo.add("Setup SLT query", System.currentTimeMillis() - lstartTime);
            LOGGER.debug("Setup SLT query:\t" + (System.currentTimeMillis() - lstartTime));
            lstartTime = System.currentTimeMillis();

            DocList subFiltered = qr.getSubSetToSearchIn(filters);
            timinginfo.add("Do Query Redux", System.currentTimeMillis() - lstartTime);
            LOGGER.debug("Do query redux:\t" + (System.currentTimeMillis() - lstartTime));
            lstartTime = System.currentTimeMillis();

            numFiltered += qr.getFiltered().docList.size();
            numSubset += subFiltered.size();
            LOGGER.info("Number of documents to search:\t" + subFiltered.size());

            slt = new SenseQuery(rtv, senseField, CKBid,
                    params.getFloat(SenseParams.SENSE_WEIGHT, SenseParams.DEFAULT_SENSE_WEIGHT), null);
            LOGGER.debug("Setup sense query:\t" + (System.currentTimeMillis() - lstartTime));
            timinginfo.add("Setup sense query", System.currentTimeMillis() - lstartTime);
            lstartTime = System.currentTimeMillis();

            sltDocs = searcher.getDocListAndSet(slt, subFiltered, Sort.RELEVANCE, 0, 1000, flags);
            timinginfo.add("Do sense query", System.currentTimeMillis() - lstartTime);
            lstartTime = System.currentTimeMillis();

            LOGGER.debug("Adding this keyto cache:\t" + key.getSet().toString());
            searcher.getCache("com.searchbox.sltcache").put(key.getSet(), sltDocs);

        } else {
            fromcache = true;
            timinginfo.add("Getting from cache", System.currentTimeMillis() - lstartTime);
            LOGGER.debug("Got result from cache");
            lstartTime = System.currentTimeMillis();
        }

        if (sltDocs == null) {
            numEmpty++;
            sltDocs = new DocListAndSet(); // avoid NPE
        }
        rsp.add("response", sltDocs.docList.subset(start, rows));

        // maybe facet the results
        if (params.getBool(FacetParams.FACET, false)) {
            if (sltDocs.docSet == null) {
                rsp.add("facet_counts", null);
            } else {
                SimpleFacets f = new SimpleFacets(req, sltDocs.docSet, params);
                rsp.add("facet_counts", f.getFacetCounts());
            }
        }
        timinginfo.add("Facet parts", System.currentTimeMillis() - lstartTime);
        LOGGER.debug("Facet parts:\t" + (System.currentTimeMillis() - lstartTime));

        // Debug info, not doing it for the moment.
        boolean dbg = req.getParams().getBool(CommonParams.DEBUG_QUERY, false);

        boolean dbgQuery = false, dbgResults = false;
        if (dbg == false) {//if it's true, we are doing everything anyway.
            String[] dbgParams = req.getParams().getParams(CommonParams.DEBUG);
            if (dbgParams != null) {
                for (int i = 0; i < dbgParams.length; i++) {
                    if (dbgParams[i].equals(CommonParams.QUERY)) {
                        dbgQuery = true;
                    } else if (dbgParams[i].equals(CommonParams.RESULTS)) {
                        dbgResults = true;
                    }
                }
            }
        } else {
            dbgQuery = true;
            dbgResults = true;
        }
        // Copied from StandardRequestHandler... perhaps it should be added to doStandardDebug?
        if (dbg == true) {
            try {
                lstartTime = System.currentTimeMillis();
                NamedList<Object> dbgInfo = SolrPluginUtils.doStandardDebug(req, q, slt,
                        sltDocs.docList.subset(start, rows), dbgQuery, dbgResults);
                dbgInfo.add("Query freqs", slt.getAllTermsasString());
                if (null != dbgInfo) {
                    if (null != filters) {
                        dbgInfo.add("filter_queries", req.getParams().getParams(CommonParams.FQ));
                        List<String> fqs = new ArrayList<String>(filters.size());
                        for (Query fq : filters) {
                            fqs.add(QueryParsing.toString(fq, req.getSchema()));
                        }
                        dbgInfo.add("parsed_filter_queries", fqs);
                    }
                    if (null != qr) {
                        dbgInfo.add("QueryReduction", qr.getDbgInfo());
                    }
                    if (null != slt) {
                        dbgInfo.add("SLT", slt.getDbgInfo());

                    }

                    dbgInfo.add("fromcache", fromcache);
                    rsp.add("debug", dbgInfo);
                    timinginfo.add("Debugging parts", System.currentTimeMillis() - lstartTime);
                    dbgInfo.add("timings", timinginfo);
                }
            } catch (Exception e) {
                SolrException.log(SolrCore.log, "Exception during debug", e);
                rsp.add("exception_during_debug", SolrException.toStr(e));
            }
        }
    } catch (Exception e) {
        numErrors++;
        e.printStackTrace();
    } finally {
        totalTime += System.currentTimeMillis() - startTime;
    }

}

From source file:com.searchbox.solr.SenseLikeThisHandlerNoReduction.java

License:Apache License

@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    SolrParams params = req.getParams();

    if (!keystate) {
        LOGGER.error(//from  w  w w  .  j  a v  a  2 s .  com
                "License key failure, not performing sense query. Please email contact@searchbox.com for more information.");
        return;
    }

    int docID;
    // Set field flags
    ReturnFields returnFields = new SolrReturnFields(req);
    rsp.setReturnFields(returnFields);
    int flags = 0;
    if (returnFields.wantsScore()) {
        flags |= SolrIndexSearcher.GET_SCORES;
    }

    String defType = params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE);
    String q = params.get(CommonParams.Q);
    Query query = null;
    SortSpec sortSpec = null;
    List<Query> filters = new ArrayList<Query>();

    try {
        if (q != null) {
            QParser parser = QParser.getParser(q, defType, req);
            query = parser.getQuery();
            sortSpec = parser.getSort(true);
        }

        String[] fqs = req.getParams().getParams(CommonParams.FQ);
        if (fqs != null && fqs.length != 0) {
            for (String fq : fqs) {
                if (fq != null && fq.trim().length() != 0) {
                    QParser fqp = QParser.getParser(fq, null, req);
                    filters.add(fqp.getQuery());
                }
            }
        }
    } catch (Exception e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
    }

    SolrIndexSearcher searcher = req.getSearcher();
    SchemaField uniqueKeyField = searcher.getSchema().getUniqueKeyField();

    DocListAndSet sltDocs = null;

    // Parse Required Params
    // This will either have a single Reader or valid query
    Reader reader = null;
    try {
        if (q == null || q.trim().length() < 1) {
            Iterable<ContentStream> streams = req.getContentStreams();
            if (streams != null) {
                Iterator<ContentStream> iter = streams.iterator();
                if (iter.hasNext()) {
                    reader = iter.next().getReader();
                }
                if (iter.hasNext()) {
                    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                            "SenseLikeThis does not support multiple ContentStreams");
                }
            }
        }

        int start = params.getInt(CommonParams.START, 0);
        int rows = params.getInt(CommonParams.ROWS, 10);

        // Find documents SenseLikeThis - either with a reader or a query
        // --------------------------------------------------------------------------------
        SenseQuery slt = null;
        if (reader != null) {
            throw new RuntimeException("SLT based on a reader is not yet implemented");
        } else if (q != null) {
            // Matching options
            boolean includeMatch = params.getBool(MoreLikeThisParams.MATCH_INCLUDE, true);
            int matchOffset = params.getInt(MoreLikeThisParams.MATCH_OFFSET, 0);
            // Find the base match

            DocList match = searcher.getDocList(query, null, null, matchOffset, 1, flags); // only get the first one...
            if (includeMatch) {
                rsp.add("match", match);
            }

            // Get docID
            DocIterator iterator = match.iterator();
            docID = iterator.nextDoc();

            BooleanQuery bq = new BooleanQuery();
            Document doc = searcher.getIndexReader().document(docID);
            bq.add(new TermQuery(new Term(uniqueKeyField.getName(),
                    uniqueKeyField.getType().storedToIndexed(doc.getField(uniqueKeyField.getName())))),
                    BooleanClause.Occur.MUST_NOT);
            filters.add(bq);

        } else {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                    "SenseLikeThis requires either a query (?q=) or text to find similar documents.");
        }

        String CKBid = params.get(SenseParams.SENSE_CKB, SenseParams.SENSE_CKB_DEFAULT);

        String senseField = params.get(SenseParams.SENSE_FIELD, SenseParams.DEFAULT_SENSE_FIELD);
        slt = new SenseQuery(new RealTermFreqVector(docID, searcher.getIndexReader(), senseField), senseField,
                CKBid, params.getFloat(SenseParams.SENSE_WEIGHT, SenseParams.DEFAULT_SENSE_WEIGHT), null);

        //Execute the SLT query
        //DocSet filtered = searcher.getDocSet(filters);
        //System.out.println("Number of documents to search:\t" + filtered.size());
        //sltDocs = searcher.getDocListAndSet(slt, filtered, Sort.RELEVANCE, start, rows, flags);
        sltDocs = searcher.getDocListAndSet(slt, filters, Sort.RELEVANCE, start, rows, flags);

    } finally {
        if (reader != null) {
            reader.close();
        }
    }

    if (sltDocs == null) {
        sltDocs = new DocListAndSet(); // avoid NPE
    }
    rsp.add("response", sltDocs.docList);

    // maybe facet the results
    if (params.getBool(FacetParams.FACET, false)) {
        if (sltDocs.docSet == null) {
            rsp.add("facet_counts", null);
        } else {
            SimpleFacets f = new SimpleFacets(req, sltDocs.docSet, params);
            rsp.add("facet_counts", f.getFacetCounts());
        }
    }

    // Debug info, not doing it for the moment.
    boolean dbg = req.getParams().getBool(CommonParams.DEBUG_QUERY, false);

    boolean dbgQuery = false, dbgResults = false;
    if (dbg == false) {//if it's true, we are doing everything anyway.
        String[] dbgParams = req.getParams().getParams(CommonParams.DEBUG);
        if (dbgParams != null) {
            for (int i = 0; i < dbgParams.length; i++) {
                if (dbgParams[i].equals(CommonParams.QUERY)) {
                    dbgQuery = true;
                } else if (dbgParams[i].equals(CommonParams.RESULTS)) {
                    dbgResults = true;
                }
            }
        }
    } else {
        dbgQuery = true;
        dbgResults = true;
    }
    // Copied from StandardRequestHandler... perhaps it should be added to doStandardDebug?
    if (dbg == true) {
        try {

            NamedList<Object> dbgInfo = SolrPluginUtils.doStandardDebug(req, q, query, sltDocs.docList,
                    dbgQuery, dbgResults);
            if (null != dbgInfo) {
                if (null != filters) {
                    dbgInfo.add("filter_queries", req.getParams().getParams(CommonParams.FQ));
                    List<String> fqs = new ArrayList<String>(filters.size());
                    for (Query fq : filters) {
                        fqs.add(QueryParsing.toString(fq, req.getSchema()));
                    }
                    dbgInfo.add("parsed_filter_queries", fqs);
                }
                rsp.add("debug", dbgInfo);
            }
        } catch (Exception e) {
            SolrException.log(SolrCore.log, "Exception during debug", e);
            rsp.add("exception_during_debug", SolrException.toStr(e));
        }
    }
}

From source file:com.searchbox.solr.SenseQueryHandler.java

@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    NamedList<Object> timinginfo = new NamedList<Object>();
    numRequests++;/*from w  w w . j a  va 2s .  co m*/
    long startTime = System.currentTimeMillis();
    long lstartTime = System.currentTimeMillis();

    if (!keystate) {
        LOGGER.error(
                "License key failure, not performing sense query. Please email contact@searchbox.com for more information.");
        return;
    }

    boolean fromcache = false;

    try {
        SolrParams params = req.getParams();
        HashSet<String> toIgnore = new HashSet<String>();
        toIgnore.add("start");
        toIgnore.add("rows");
        toIgnore.add("fl");
        toIgnore.add("wt");
        toIgnore.add("indent");

        SolrCacheKey key = new SolrCacheKey(params, toIgnore);

        // Set field flags
        ReturnFields returnFields = new SolrReturnFields(req);
        rsp.setReturnFields(returnFields);
        int flags = 0;
        if (returnFields.wantsScore()) {
            flags |= SolrIndexSearcher.GET_SCORES;
        }

        String defType = params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE);
        String q = params.get(CommonParams.Q);
        Query query = null;
        QueryReductionFilter qr = null;
        List<Query> filters = new ArrayList<Query>();

        try {
            if (q != null) {
                QParser parser = QParser.getParser(q, defType, req);
                query = parser.getQuery();

            }

            String[] fqs = req.getParams().getParams(CommonParams.FQ);
            if (fqs != null && fqs.length != 0) {
                for (String fq : fqs) {
                    if (fq != null && fq.trim().length() != 0) {
                        QParser fqp = QParser.getParser(fq, null, req);
                        filters.add(fqp.getQuery());
                    }
                }
            }
        } catch (Exception e) {
            numErrors++;
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
        }

        int start = params.getInt(CommonParams.START, 0);
        int rows = params.getInt(CommonParams.ROWS, 10);

        SenseQuery slt = null;
        if (q == null) {
            numErrors++;
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                    "SenseLikeThis requires either a query (?q=) or text to find similar documents.");
        }

        timinginfo.add("Parse Query time", System.currentTimeMillis() - lstartTime);
        LOGGER.debug("Parsed Query Time:\t" + (System.currentTimeMillis() - lstartTime));
        lstartTime = System.currentTimeMillis();

        SolrIndexSearcher searcher = req.getSearcher();
        SolrCache sc = searcher.getCache("com.searchbox.sltcache");
        DocListAndSet sltDocs = null;
        if (sc != null) {
            //try to get from cache
            sltDocs = (DocListAndSet) sc.get(key.getSet());
        } else {
            LOGGER.error("com.searchbox.sltcache not defined, can't cache slt queries");
        }

        if (start + rows > 1000 || sltDocs == null || !params.getBool(CommonParams.CACHE, true)) { //not in cache, need to do search
            String CKBid = params.get(SenseParams.SENSE_CKB, SenseParams.SENSE_CKB_DEFAULT);
            String senseField = params.get(SenseParams.SENSE_FIELD, SenseParams.DEFAULT_SENSE_FIELD);
            RealTermFreqVector rtv = new RealTermFreqVector(q,
                    SenseQuery.getAnalyzerForField(req.getSchema(), senseField));
            timinginfo.add("Make real term freq vector", System.currentTimeMillis() - lstartTime);
            lstartTime = System.currentTimeMillis();

            qr = new QueryReductionFilter(rtv, CKBid, searcher, senseField);
            qr.setNumtermstouse(params.getInt(SenseParams.SENSE_QR_NTU, SenseParams.SENSE_QR_NTU_DEFAULT));

            numTermsUsed += qr.getNumtermstouse();
            numTermsConsidered += rtv.getSize();

            qr.setThreshold(params.getInt(SenseParams.SENSE_QR_THRESH, SenseParams.SENSE_QR_THRESH_DEFAULT));
            qr.setMaxDocSubSet(params.getInt(SenseParams.SENSE_QR_MAXDOC, SenseParams.SENSE_QR_MAXDOC_DEFAULT));
            qr.setMinDocSetSizeForFilter(
                    params.getInt(SenseParams.SENSE_MINDOC4QR, SenseParams.SENSE_MINDOC4QR_DEFAULT));

            timinginfo.add("Setup Sense query", System.currentTimeMillis() - lstartTime);
            LOGGER.debug("Setup Sense query:\t" + (System.currentTimeMillis() - lstartTime));
            lstartTime = System.currentTimeMillis();

            DocList subFiltered = qr.getSubSetToSearchIn(filters);
            timinginfo.add("Do Query Redux", System.currentTimeMillis() - lstartTime);
            LOGGER.debug("Do query redux:\t" + (System.currentTimeMillis() - lstartTime));
            lstartTime = System.currentTimeMillis();

            numFiltered += qr.getFiltered().docList.size();
            numSubset += subFiltered.size();
            LOGGER.info("Number of documents to search:\t" + subFiltered.size());

            slt = new SenseQuery(rtv, senseField, CKBid,
                    params.getFloat(SenseParams.SENSE_WEIGHT, SenseParams.DEFAULT_SENSE_WEIGHT), null);
            LOGGER.debug("Setup sense query:\t" + (System.currentTimeMillis() - lstartTime));
            timinginfo.add("Setup sense query", System.currentTimeMillis() - lstartTime);
            lstartTime = System.currentTimeMillis();

            sltDocs = searcher.getDocListAndSet(slt, subFiltered, Sort.RELEVANCE, 0, 1000, flags);
            timinginfo.add("Do sense query", System.currentTimeMillis() - lstartTime);
            lstartTime = System.currentTimeMillis();

            LOGGER.debug("Adding this keyto cache:\t" + key.getSet().toString());
            searcher.getCache("com.searchbox.sltcache").put(key.getSet(), sltDocs);

        } else {
            fromcache = true;
            timinginfo.add("Getting from cache", System.currentTimeMillis() - lstartTime);
            LOGGER.debug("Got result from cache");
            lstartTime = System.currentTimeMillis();
        }

        if (sltDocs == null) {
            numEmpty++;
            sltDocs = new DocListAndSet(); // avoid NPE
        }
        rsp.add("response", sltDocs.docList.subset(start, rows));

        // --------- OLD CODE BELOW
        // maybe facet the results
        if (params.getBool(FacetParams.FACET, false)) {
            if (sltDocs.docSet == null) {
                rsp.add("facet_counts", null);
            } else {
                SimpleFacets f = new SimpleFacets(req, sltDocs.docSet, params);
                rsp.add("facet_counts", f.getFacetCounts());
            }
        }

        // Debug info, not doing it for the moment.
        boolean dbg = req.getParams().getBool(CommonParams.DEBUG_QUERY, false);

        boolean dbgQuery = false, dbgResults = false;
        if (dbg == false) {//if it's true, we are doing everything anyway.
            String[] dbgParams = req.getParams().getParams(CommonParams.DEBUG);
            if (dbgParams != null) {
                for (int i = 0; i < dbgParams.length; i++) {
                    if (dbgParams[i].equals(CommonParams.QUERY)) {
                        dbgQuery = true;
                    } else if (dbgParams[i].equals(CommonParams.RESULTS)) {
                        dbgResults = true;
                    }
                }
            }
        } else {
            dbgQuery = true;
            dbgResults = true;
        }
        if (dbg == true) {
            try {
                NamedList dbgInfo = new SimpleOrderedMap();
                dbgInfo.add("Query freqs", slt.getAllTermsasString());
                dbgInfo.addAll(
                        getExplanations(slt, sltDocs.docList.subset(start, rows), searcher, req.getSchema()));
                if (null != filters) {
                    dbgInfo.add("filter_queries", req.getParams().getParams(CommonParams.FQ));
                    List<String> fqs = new ArrayList<String>(filters.size());
                    for (Query fq : filters) {
                        fqs.add(QueryParsing.toString(fq, req.getSchema()));
                    }
                    dbgInfo.add("parsed_filter_queries", fqs);
                }
                if (null != qr) {
                    dbgInfo.add("QueryReduction", qr.getDbgInfo());
                }
                if (null != slt) {
                    dbgInfo.add("SLT", slt.getDbgInfo());

                }
                dbgInfo.add("fromcache", fromcache);
                rsp.add("debug", dbgInfo);
                timinginfo.add("Debugging parts", System.currentTimeMillis() - lstartTime);
                dbgInfo.add("timings", timinginfo);

            } catch (Exception e) {
                SolrException.log(SolrCore.log, "Exception during debug", e);
                rsp.add("exception_during_debug", SolrException.toStr(e));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        numErrors++;
    } finally {
        totalTime += System.currentTimeMillis() - startTime;
    }
}

From source file:com.sn.solr.plugin.comp.RankComponent.java

License:Apache License

/**
 * <p>//from  www  . ja v a2  s. c  om
 * Calls super.process() to complete the processing required by parent. 
 * Constructs new response with results from previous processing that needs
 * to be returned with additional rank response.
 * 
 * <p>
 * Executes call to compute appropriate ranking based on the strategy 
 * requested & adds the computed rank values to each document. Finally 
 * removes the additional response data forced by this component that was 
 * not intended by user request.
 * 
 * @param rb ResponseBuilder
 */
@SuppressWarnings("deprecation")
@Override
public void process(ResponseBuilder rb) throws IOException {
    //Complete parent component process
    super.process(rb);
    long startTime = System.nanoTime();
    //Prepare Params
    SolrParams params = rb.req.getParams();
    RankStrategy rankStrategy = getRankStrategy(params);
    String idField = getIdField(params);
    String rankField = getRankField(params);
    SolrQuery.ORDER rankFieldSort = getRankFieldSortOrder(params, rankField);
    LOG.info("Params Passed - RankStrategy: {} IdField: {} RankField: {} RankSort: {}",
            new Object[] { rankStrategy, idField, rankField, rankFieldSort });
    //Construct New Response derived from response from previous chain
    SolrDocumentList docList = SolrHelper.getSolrDocList(rb.req, rb.rsp);
    rb.rsp.add(RESP_EL_TAG, docList);

    //Process ranking
    Map<String, Number> rankMap = null;
    List<Pair<String, Number>> pairList = null;
    if (rankStrategy.equals(RankStrategy.LEGACY_DENSE)) {
        rankMap = RankEngine.computeLegacyDenseRank(rb, idField, rankField);
    } else if (rankStrategy.equals(RankStrategy.ORDINAL)) {
        pairList = SolrHelper.createPairList(docList, idField);
        String _start = rb.req.getParams().get(CommonParams.START);
        int start = 0;
        if (_start != null && AppHelper.isInteger(_start))
            start = new Integer(_start);
        rankMap = RankEngine.computeOrdinalBasedRank(pairList, start);
    } else {
        pairList = SolrHelper.createPairList(SolrHelper.getFacetsByField(rb.rsp, rankField), rankFieldSort);
        rankMap = RankEngine.computeFacetBasedRank(pairList, rankStrategy);
    }
    LOG.debug("RANK MAP: ", rankMap);

    //Add computed ranks to response
    for (SolrDocument d : docList) {
        if (rankStrategy.equals(RankStrategy.ORDINAL) || rankStrategy.equals(RankStrategy.LEGACY_DENSE)) {
            d.addField(RANK_TAG, rankMap.get(d.get(idField)));
        } else {
            d.addField(RANK_TAG, rankMap.get(d.get(rankField)));
        }
    }

    //Finally remove any facet results from response
    if (rb.rsp.getValues() != null) {
        rb.rsp.getValues().remove(SolrHelper.FACET_CNT_TAG);
    }
    rb.rsp.getValues().remove(RESP_EL_TAG);
    LOG.info("SolrUtils - Rank Component Time: {}", AppHelper.getDiffTime(startTime));
}

From source file:com.sn.solr.plugin.rank.RankEngine.java

License:Apache License

/**
 * Provides implementation for Dense ranking ["1223"] as identified by the
 * {@link RankStrategy#LEGACY_DENSE} the difference is that this
 * implementation is computed without using facet results so this will 
 * noticeably slower than computing rank based on facets
 * use {@link RankStrategy#DENSE}. Besides this implementation might cause 
 * lot of cache evictions putting stress on memory. 
 *
 * @see #computeDenseRank(List)/*from  w ww.ja  v  a2 s  . co m*/
 * 
 * @param pairList List of {@link Pair} objects that holds the value of rank 
 * field & respective count.
 */
@Deprecated
public static Map<String, Number> computeLegacyDenseRank(ResponseBuilder rb, String idField, String rankField)
        throws IOException {
    SolrIndexSearcher searcher = rb.req.getSearcher();
    SolrParams params = rb.req.getParams();// .getParams(FacetParams.FACET_FIELD);

    String _start = params.get(CommonParams.START);
    String _rows = params.get(CommonParams.ROWS);
    int start = 0;
    int rows = 10;

    if (_start != null & AppHelper.isInteger(_start))
        start = new Integer(_start);
    if (_rows != null & AppHelper.isInteger(_rows))
        rows = new Integer(_rows);

    LOG.info("Computing rank using strategy: {}", RankStrategy.ORDINAL.getDescription());
    FieldSelector fs = new MapFieldSelector(new String[] { idField, rankField });
    Map<String, Number> rankMap = new HashMap<String, Number>();
    DocList docs = searcher.getDocList(rb.getQuery(), rb.getFilters(), rb.getSortSpec().getSort(), 0,
            start + rows, 0);
    int denseRank = 1;
    int _CurrScore = 0;
    int _PrevScore = 0;
    int i = 0;
    for (DocIterator it = docs.iterator(); it.hasNext();) {
        Document doc = searcher.doc(it.nextDoc(), fs);
        _CurrScore = new Integer(doc.get(rankField));
        if (i == 0) {
            _PrevScore = _CurrScore;
        }
        if (_PrevScore != _CurrScore) {
            _PrevScore = _CurrScore;
            denseRank++;
        }
        if (i >= start) {
            rankMap.put(doc.get(idField), denseRank);
        }
        i++;
    }

    return rankMap;
}

From source file:com.sn.solr.utils.comp.RankComponent.java

License:Apache License

/**
 * <p>//from  www  .  j a  v  a  2  s  .  co  m
 * Calls super.process() to complete the processing required by parent. 
 * Constructs new response with results from previous processing that needs
 * to be returned with additional rank response.
 * 
 * <p>
 * Executes call to compute appropriate ranking based on the strategy 
 * requested & adds the computed rank values to each document. Finally 
 * removes the additional response data forced by this component that was 
 * not intended by user request.
 * 
 * @param rb ResponseBuilder
 */
@SuppressWarnings("deprecation")
@Override
public void process(ResponseBuilder rb) throws IOException {
    //Complete parent component process
    super.process(rb);
    long startTime = System.nanoTime();
    //Prepare Params
    SolrParams params = rb.req.getParams();
    RankStrategy rankStrategy = getRankStrategy(params);
    String idField = getIdField(params);
    String rankField = getRankField(params);
    SolrQuery.ORDER rankFieldSort = getRankFieldSortOrder(params, rankField);
    LOG.info("Params Passed - RankStrategy: {} IdField: {} RankField: {} RankSort: {}",
            new Object[] { rankStrategy, idField, rankField, rankFieldSort });
    //Construct New Response derived from response from previous chain
    SolrDocumentList docList = SolrHelper.getSolrDocList(rb.req, rb.rsp);
    rb.rsp.add(RESP_EL_TAG, docList);

    //Process ranking
    Map<String, Number> rankMap = null;
    List<Pair<String, Number>> pairList = null;
    if (rankStrategy.equals(RankStrategy.LEGACY_DENSE)) {
        rankMap = RankEngine.computeLegacyDenseRank(rb, idField, rankField);
    } else if (rankStrategy.equals(RankStrategy.ORDINAL)) {
        pairList = SolrHelper.createPairList(docList, idField);
        String _start = rb.req.getParams().get(CommonParams.START);
        int start = 0;
        if (_start != null && AppHelper.isInteger(_start))
            start = new Integer(_start);
        rankMap = RankEngine.computeOrdinalBasedRank(pairList, start);
    } else {
        pairList = SolrHelper.createPairList(SolrHelper.getFacetsByField(rb.rsp, rankField), rankFieldSort);
        rankMap = RankEngine.computeFacetBasedRank(pairList, rankStrategy);
    }

    //Add computed ranks to response
    for (SolrDocument d : docList) {
        if (rankStrategy.equals(RankStrategy.ORDINAL) || rankStrategy.equals(RankStrategy.LEGACY_DENSE)) {
            d.addField(RANK_TAG, rankMap.get(d.get(idField)));
        } else {
            d.addField(RANK_TAG, rankMap.get(d.get(rankField)));
        }
    }

    //Finally remove any facet results from response
    if (rb.rsp.getValues() != null) {
        rb.rsp.getValues().remove(SolrHelper.FACET_CNT_TAG);
    }
    rb.rsp.getValues().remove(RESP_EL_TAG);
    LOG.info("SolrUtils - Rank Component Time: {}", AppHelper.getDiffTime(startTime));
}