Example usage for org.apache.solr.search SortSpec getSort

List of usage examples for org.apache.solr.search SortSpec getSort

Introduction

In this page you can find the example usage for org.apache.solr.search SortSpec getSort.

Prototype

public Sort getSort() 

Source Link

Document

Gets the Lucene Sort object, or null for the default sort by score descending.

Usage

From source file:org.dfdeshom.solr.mlt.MoreLikeThisHandler.java

License:Apache License

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

    // Set field flags
    ReturnFields returnFields = new SolrReturnFields(req);
    rsp.setReturnFields(returnFields);//from  ww w.  ja v a  2  s .c o  m
    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 = null;
    QParser parser = null;

    try {
        if (q != null) {
            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) {
            filters = new ArrayList<Query>();
            for (String fq : fqs) {
                if (fq != null && fq.trim().length() != 0) {
                    QParser fqp = QParser.getParser(fq, null, req);
                    filters.add(fqp.getQuery());
                }
            }
        }
    } catch (SyntaxError e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
    }

    SolrIndexSearcher searcher = req.getSearcher();

    MoreLikeThisHelper mlt = new MoreLikeThisHelper(params, searcher);

    // Hold on to the interesting terms if relevant
    TermStyle termStyle = TermStyle.get(params.get(MoreLikeThisParams.INTERESTING_TERMS));
    List<InterestingTerm> interesting = (termStyle == TermStyle.NONE) ? null
            : new ArrayList<InterestingTerm>(mlt.mlt.getMaxQueryTerms());

    DocListAndSet mltDocs = 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,
                            "MoreLikeThis does not support multiple ContentStreams");
                }
            }
        }

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

        // Find documents MoreLikeThis - either with a reader or a query
        // --------------------------------------------------------------------------------
        if (reader != null) {
            mltDocs = mlt.getMoreLikeThis(reader, sortSpec.getSort(), start, rows, filters, interesting, flags);
        } 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);
            }

            // This is an iterator, but we only handle the first match
            DocIterator iterator = match.iterator();
            if (iterator.hasNext()) {
                // do a MoreLikeThis query for each document in results
                int id = iterator.nextDoc();
                mltDocs = mlt.getMoreLikeThis(parser, id, sortSpec.getSort(), start, rows, filters, interesting,
                        flags);
            }
        } else {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                    "MoreLikeThis requires either a query (?q=) or text to find similar documents.");
        }

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

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

    if (interesting != null) {
        if (termStyle == TermStyle.DETAILS) {
            NamedList<Float> it = new NamedList<Float>();
            for (InterestingTerm t : interesting) {
                it.add(t.term.toString(), t.boost);
            }
            rsp.add("interestingTerms", it);
        } else {
            List<String> it = new ArrayList<String>(interesting.size());
            for (InterestingTerm t : interesting) {
                it.add(t.term.text());
            }
            rsp.add("interestingTerms", it);
        }
    }

    // maybe facet the results
    if (params.getBool(FacetParams.FACET, false)) {
        if (mltDocs.docSet == null) {
            rsp.add("facet_counts", null);
        } else {
            SimpleFacets f = new SimpleFacets(req, mltDocs.docSet, params);
            rsp.add("facet_counts", f.getFacetCounts());
        }
    }
    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, mlt.getRawMLTQuery(),
                    mltDocs.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:org.dice.solrenhancements.morelikethis.DiceMoreLikeThisHandler.java

License:Apache License

@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    // set and override parameters
    SolrIndexSearcher searcher = req.getSearcher();
    SchemaField uniqueKeyField = searcher.getSchema().getUniqueKeyField();
    ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
    configureSolrParameters(req, params, uniqueKeyField.getName());

    // Set field flags
    ReturnFields returnFields = new SolrReturnFields(req);
    rsp.setReturnFields(returnFields);//w  w w.  j a v a 2  s.  c  om
    int flags = 0;
    if (returnFields.wantsScore()) {
        flags |= SolrIndexSearcher.GET_SCORES;
    }
    // note: set in configureSolrParameters
    String defType = params.get(QueryParsing.DEFTYPE, EDISMAX);
    String q = params.get(CommonParams.Q);
    Query query = null;
    SortSpec sortSpec = null;
    QParser parser = null;

    List<Query> targetFqFilters = null;
    List<Query> mltFqFilters = null;

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

        targetFqFilters = getFilters(req, CommonParams.FQ);
        mltFqFilters = getFilters(req, MoreLikeThisParams.FQ);
    } catch (SyntaxError e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
    }

    MoreLikeThisHelper mlt = new MoreLikeThisHelper(params, searcher, uniqueKeyField, parser);

    // Hold on to the interesting terms if relevant
    MoreLikeThisParams.TermStyle termStyle = MoreLikeThisParams.TermStyle
            .get(params.get(MoreLikeThisParams.INTERESTING_TERMS));

    MLTResult mltResult = null;
    DocListAndSet mltDocs = null;

    // Parse Required Params
    // This will either have a single Reader or valid query
    Reader reader = null;
    try {
        int start = params.getInt(CommonParams.START, 0);
        int rows = params.getInt(CommonParams.ROWS, 10);

        // for use when passed a content stream
        if (q == null || q.trim().length() < 1) {
            reader = getContentStreamReader(req, reader);
        }
        // Find documents MoreLikeThis - either with a reader or a query
        // --------------------------------------------------------------------------------
        if (reader != null) {
            // this will only be initialized if used with a content stream (see above)
            mltResult = mlt.getMoreLikeThisFromContentSteam(reader, start, rows, mltFqFilters, flags,
                    sortSpec.getSort());
        } else if (q != null) {
            // Matching options
            mltResult = getMoreLikeTheseFromQuery(rsp, params, flags, q, query, sortSpec, targetFqFilters,
                    mltFqFilters, searcher, mlt, start, rows);
        } else {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                    "MoreLikeThis requires either a query (?q=) or text to find similar documents.");
        }
        if (mltResult != null) {
            mltDocs = mltResult.getDoclist();
        }

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

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

    if (mltResult != null && termStyle != MoreLikeThisParams.TermStyle.NONE) {
        addInterestingTerms(rsp, termStyle, mltResult);
    }

    // maybe facet the results
    if (params.getBool(FacetParams.FACET, false)) {
        addFacet(req, rsp, params, mltDocs);
    }

    addDebugInfo(req, rsp, q, mltFqFilters, mlt, mltResult);
}

From source file:org.dice.solrenhancements.morelikethis.DiceMoreLikeThisHandler.java

License:Apache License

private MLTResult getMoreLikeTheseFromQuery(SolrQueryResponse rsp, SolrParams params, int flags, String q,
        Query query, SortSpec sortSpec, List<Query> targetFqFilters, List<Query> mltFqFilters,
        SolrIndexSearcher searcher, MoreLikeThisHelper mlt, int start, int rows)
        throws IOException, SyntaxError {

    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, targetFqFilters, null, matchOffset, 10000, flags); // only get the first one...
    if (match.matches() == 0) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                String.format("MoreLikeThis was unable to find any documents matching the query: '%s'.", q));
    }//w w w . j  a v  a2s. c om

    if (includeMatch) {
        rsp.add("match", match);
    }

    // This is an iterator, but we only handle the first match
    DocIterator iterator = match.iterator();
    if (iterator.hasNext()) {
        // do a MoreLikeThis query for each document in results
        return mlt.getMoreLikeTheseFromDocs(iterator, start, rows, mltFqFilters, flags, sortSpec.getSort());
    }
    return null;
}

From source file:org.dice.solrenhancements.unsupervisedfeedback.DiceUnsupervisedFeedbackHandler.java

License:Apache License

private DocListAndSet expandQueryAndReExecute(SolrQueryResponse rsp, SolrParams params, int maxDocumentsToMatch,
        int flags, String q, Query seedQuery, SortSpec sortSpec, List<Query> targetFqFilters,
        List<Query> mltFqFilters, SolrIndexSearcher searcher, UnsupervisedFeedbackHelper uff,
        List<InterestingTerm> interesting, DocListAndSet mltDocs, int start, int rows)
        throws IOException, SyntaxError {

    boolean includeMatch = params.getBool(UnsupervisedFeedbackParams.MATCH_INCLUDE, true);
    int matchOffset = params.getInt(UnsupervisedFeedbackParams.MATCH_OFFSET, 0);
    // Find the base match
    DocList match = searcher.getDocList(seedQuery, targetFqFilters, null, matchOffset, maxDocumentsToMatch,
            flags); // only get the first one...
    if (match.matches() == 0) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, String.format(
                "Unsupervised feedback handler was unable to find any documents matching the seed query: '%s'.",
                q));/*from  www  .  ja  v  a 2s . c o m*/
    }

    if (includeMatch) {
        rsp.add("match", match);
    }

    // This is an iterator, but we only handle the first match
    DocIterator iterator = match.iterator();
    if (iterator.hasNext()) {
        // do a MoreLikeThis query for each document in results
        mltDocs = uff.expandQueryAndReExecute(iterator, seedQuery, start, rows, mltFqFilters, interesting,
                flags, sortSpec.getSort());
    }
    return mltDocs;
}