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

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

Introduction

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

Prototype

String FQ

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

Click Source Link

Document

Lucene query string(s) for filtering the results without affecting scoring

Usage

From source file:opennlp.tools.similarity.apps.solr.IterativeQueryComponent.java

License:Apache License

private ResponseBuilder substituteField(ResponseBuilder rb, String newFieldName) {
    SolrParams params = rb.req.getParams();
    String query = params.get("q");
    String currField = StringUtils.substringBetween(" " + query, " ", ":");
    if (currField != null && newFieldName != null)
        query = query.replace(currField, newFieldName);
    NamedList values = params.toNamedList();
    values.remove("q");
    values.add("q", query);
    params = SolrParams.toSolrParams(values);
    rb.req.setParams(params);/* w  ww  .ja  v a  2 s  . c  o m*/
    rb.setQueryString(query);

    String defType = params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE);

    // get it from the response builder to give a different component a chance
    // to set it.
    String queryString = rb.getQueryString();
    if (queryString == null) {
        // this is the normal way it's set.
        queryString = params.get(CommonParams.Q);
        rb.setQueryString(queryString);
    }

    QParser parser = null;
    try {
        parser = QParser.getParser(rb.getQueryString(), defType, rb.req);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Query q = null;
    try {
        q = parser.getQuery();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if (q == null) {
        // normalize a null query to a query that matches nothing
        q = new BooleanQuery();
    }
    rb.setQuery(q);
    try {
        rb.setSortSpec(parser.getSort(true));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    rb.setQparser(parser);
    /*   try {
          rb.setScoreDoc(parser.getPaging());
       } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
       }
    */
    String[] fqs = rb.req.getParams().getParams(CommonParams.FQ);
    if (fqs != null && fqs.length != 0) {
        List<Query> filters = rb.getFilters();
        if (filters == null) {
            filters = new ArrayList<Query>(fqs.length);
        }
        for (String fq : fqs) {
            if (fq != null && fq.trim().length() != 0) {
                QParser fqp = null;
                try {
                    fqp = QParser.getParser(fq, null, rb.req);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                try {
                    filters.add(fqp.getQuery());
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        // only set the filters if they are not empty otherwise
        // fq=&someotherParam= will trigger all docs filter for every request 
        // if filter cache is disabled
        if (!filters.isEmpty()) {
            rb.setFilters(filters);
        }
    }

    return rb;
}

From source file:opennlp.tools.similarity.apps.solr.IterativeSearchRequestHandler.java

License:Apache License

public void handleRequestBody1(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {

    // extract params from request
    SolrParams params = req.getParams();
    String q = params.get(CommonParams.Q);
    String[] fqs = params.getParams(CommonParams.FQ);
    int start = 0;
    try {/*  w  ww  . j  av  a2s .  co m*/
        start = Integer.parseInt(params.get(CommonParams.START));
    } catch (Exception e) {
        /* default */ }
    int rows = 0;
    try {
        rows = Integer.parseInt(params.get(CommonParams.ROWS));
    } catch (Exception e) {
        /* default */ }
    //SolrPluginUtils.setReturnFields(req, rsp);

    // build initial data structures

    SolrDocumentList results = new SolrDocumentList();
    SolrIndexSearcher searcher = req.getSearcher();
    Map<String, SchemaField> fields = req.getSchema().getFields();
    int ndocs = start + rows;
    Filter filter = buildFilter(fqs, req);
    Set<Integer> alreadyFound = new HashSet<Integer>();

    // invoke the various sub-handlers in turn and return results
    doSearch1(results, searcher, q, filter, ndocs, req, fields, alreadyFound);

    // ... more sub-handler calls here ...

    // build and write response
    float maxScore = 0.0F;
    int numFound = 0;
    List<SolrDocument> slice = new ArrayList<SolrDocument>();
    for (Iterator<SolrDocument> it = results.iterator(); it.hasNext();) {
        SolrDocument sdoc = it.next();
        Float score = (Float) sdoc.getFieldValue("score");
        if (maxScore < score) {
            maxScore = score;
        }
        if (numFound >= start && numFound < start + rows) {
            slice.add(sdoc);
        }
        numFound++;
    }
    results.clear();
    results.addAll(slice);
    results.setNumFound(numFound);
    results.setMaxScore(maxScore);
    results.setStart(start);
    rsp.add("response", results);

}

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

License:Open Source License

private void doUpdateDescendantDocs(NodeMetaData parentNodeMetaData, boolean overwrite,
        SolrQueryRequest request, UpdateRequestProcessor processor, LinkedHashSet<Long> stack)
        throws AuthenticationException, IOException, JSONException {

    // skipDescendantDocsForSpecificAspects is initialised on a synchronised method, so access must be also synchronised 
    synchronized (this) {
        if ((skipDescendantDocsForSpecificTypes
                && typesForSkippingDescendantDocs.contains(parentNodeMetaData.getType()))
                || (skipDescendantDocsForSpecificAspects
                        && shouldBeIgnoredByAnyAspect(parentNodeMetaData.getAspects()))) {
            return;
        }/*from   w w  w  .j av  a  2 s  .  c  om*/
    }

    Set<Long> childIds = new HashSet<>();

    if (parentNodeMetaData.getChildIds() != null) {
        childIds.addAll(parentNodeMetaData.getChildIds());
    }

    String query = FIELD_PARENT + ":\"" + parentNodeMetaData.getNodeRef() + "\"";
    ModifiableSolrParams params = new ModifiableSolrParams(request.getParams()).set(CommonParams.Q, query)
            .set(CommonParams.FL, FIELD_SOLR4_ID);

    if (skippingDocsQueryString != null && !skippingDocsQueryString.isEmpty()) {
        params.set(CommonParams.FQ, "NOT ( " + skippingDocsQueryString + " )");
    }

    SolrDocumentList docs = cloud.getSolrDocumentList(nativeRequestHandler, request, params);
    for (SolrDocument doc : docs) {
        String id = getFieldValueString(doc, FIELD_SOLR4_ID);
        TenantAclIdDbId ids = AlfrescoSolrDataModel.decodeNodeDocumentId(id);
        childIds.add(ids.dbId);
    }

    for (Long childId : childIds) {
        NodeMetaDataParameters nmdp = new NodeMetaDataParameters();
        nmdp.setFromNodeId(childId);
        nmdp.setToNodeId(childId);
        nmdp.setIncludeAclId(false);
        nmdp.setIncludeAspects(false);
        nmdp.setIncludeChildAssociations(false);
        nmdp.setIncludeChildIds(true);
        nmdp.setIncludeNodeRef(false);
        nmdp.setIncludeOwner(false);
        nmdp.setIncludeParentAssociations(false);
        // We only care about the path and ancestors (which is included) for this case
        nmdp.setIncludePaths(true);
        nmdp.setIncludeProperties(false);
        nmdp.setIncludeType(false);
        nmdp.setIncludeTxnId(false);
        // Gets only one
        List<NodeMetaData> nodeMetaDatas = repositoryClient.getNodesMetaData(nmdp, 1);

        if (!nodeMetaDatas.isEmpty()) {
            NodeMetaData nodeMetaData = nodeMetaDatas.get(0);
            if (mayHaveChildren(nodeMetaData)) {
                updateDescendantDocs(nodeMetaData, overwrite, request, processor, stack);
            }

            try {
                lock(childId);

                LOGGER.debug("Cascade update child doc {}", childId);

                // Gets the document that we have from the content store and updates it
                String fixedTenantDomain = AlfrescoSolrDataModel.getTenantId(nodeMetaData.getTenantDomain());
                SolrInputDocument cachedDoc = solrContentStore
                        .retrieveDocFromSolrContentStore(fixedTenantDomain, nodeMetaData.getId());

                if (cachedDoc != null) {
                    updatePathRelatedFields(nodeMetaData, cachedDoc);
                    updateNamePathRelatedFields(nodeMetaData, cachedDoc);
                    updateAncestorRelatedFields(nodeMetaData, cachedDoc);

                    AddUpdateCommand addDocCmd = new AddUpdateCommand(request);
                    addDocCmd.overwrite = overwrite;
                    addDocCmd.solrDoc = cachedDoc;

                    processor.processAdd(addDocCmd);
                    solrContentStore.storeDocOnSolrContentStore(fixedTenantDomain, nodeMetaData.getId(),
                            cachedDoc);
                } else {
                    LOGGER.debug("No child doc found to update {}", childId);
                }
            } finally {
                unlock(childId);
            }
        }
    }
}

From source file:org.alfresco.solr.tracker.CascadeTrackerTest.java

License:Open Source License

/**
 * After updating the test data hierarchy (folders and file), the test checks that the cascade tracker properly
 * reflects the changes in the index./*  w  w w .  j a v  a 2 s  .  com*/
 */
@Test
public void solrTracking_folderUpdate_shouldReIndexFolderAndChildren() throws Exception {
    // Update the folder
    Transaction txn = getTransaction(0, 1);

    folderMetaData.getProperties().put(ContentModel.PROP_CASCADE_TX,
            new StringPropertyValue(Long.toString(txn.getId())));
    folderMetaData.getProperties().put(ContentModel.PROP_NAME, new StringPropertyValue("folder2"));
    folderNode.setTxnId(txn.getId());
    folderMetaData.setTxnId(txn.getId());

    // Change the ancestor on the file just to see if it's been updated
    NodeRef nodeRef = new NodeRef(new StoreRef("workspace", "SpacesStore"), createGUID());
    childFolderMetaData.setAncestors(ancestors(nodeRef));
    fileMetaData.setAncestors(ancestors(nodeRef));

    upsertData(txn, singletonList(folderNode), singletonList(folderMetaData));

    // Check that the ancestor has been changed and indexed
    TermQuery query = new TermQuery(new Term(QueryConstants.FIELD_ANCESTOR, nodeRef.toString()));
    waitForDocCount(query, 2, MAX_WAIT_TIME);

    // Child folder and grandchild document must be updated
    // This is the same query as before but instead of using a Lucene query, it uses the /afts endpoint (request handler)
    ModifiableSolrParams params = new ModifiableSolrParams()
            .add(CommonParams.Q, QueryConstants.FIELD_ANCESTOR + ":\"" + nodeRef.toString() + "\"")
            .add(CommonParams.QT, "/afts").add(CommonParams.START, "0").add(CommonParams.ROWS, "6")
            .add(CommonParams.SORT, "id asc").add(CommonParams.FQ, "{!afts}AUTHORITY_FILTER_FROM_JSON");

    SolrServletRequest req = areq(params,
            "{\"locales\":[\"en\"], \"templates\": [{\"name\":\"t1\", \"template\":\"%cm:content\"}], \"authorities\": [ \"mike\"], \"tenants\": [ \"\" ]}");

    assertQ(req, "*[count(//doc)=2]", "//result/doc[1]/long[@name='DBID'][.='" + childFolderNode.getId() + "']",
            "//result/doc[2]/long[@name='DBID'][.='" + fileNode.getId() + "']");
}

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 w  w  w. ja  va2 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);/*from   ww w.  j  a v  a2  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 void addDebugInfo(SolrQueryRequest req, SolrQueryResponse rsp, String q, List<Query> mltFqFilters,
        MoreLikeThisHelper mlt, MLTResult mltResult) {
    DocListAndSet mltDocs = mltResult.getDoclist();

    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;// w w  w .  j  a  v a2  s  . c  o  m
                } 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<String> it = getMltTermsForDebug(mltResult);

            NamedList<Object> dbgInfo = new NamedList<Object>();
            NamedList<Object> stdDbg = SolrPluginUtils.doStandardDebug(req, q, mlt.getRealMLTQuery(),
                    mltDocs.docList, dbgQuery, dbgResults);
            if (null != dbgInfo) {
                rsp.add("debug", dbgInfo);
                dbgInfo.add("mltTerms", it);
                dbgInfo.addAll(stdDbg);

                if (null != mltFqFilters) {
                    dbgInfo.add("filter_queries", req.getParams().getParams(CommonParams.FQ));
                    List<String> fqs = new ArrayList<String>(mltFqFilters.size());
                    for (Query fq : mltFqFilters) {
                        fqs.add(QueryParsing.toString(fq, req.getSchema()));
                    }
                    dbgInfo.add("mlt_filter_queries", fqs);
                }
            }
        } 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.unsupervisedfeedback.DiceUnsupervisedFeedbackHandler.java

License:Apache License

@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    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  va 2  s .c  om
    int flags = 0;
    if (returnFields.wantsScore()) {
        flags |= SolrIndexSearcher.GET_SCORES;
    }

    String defType = params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE);
    int maxDocumentsToMatch = params.getInt(UnsupervisedFeedbackParams.MAX_DOCUMENTS_TO_PROCESS,
            UnsupervisedFeedback.DEFAULT_MAX_NUM_DOCUMENTS_TO_PROCESS);
    String q = params.get(CommonParams.Q);
    Query query = null;
    SortSpec sortSpec = null;
    QParser parser = null;

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

    try {

        parser = QParser.getParser(q, defType, req);
        query = parser.getQuery();
        sortSpec = parser.getSort(true);

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

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

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

    DocListAndSet uffDocs = 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);

        // Find documents MoreLikeThis - either with a reader or a query
        // --------------------------------------------------------------------------------
        if (q == null) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                    "Dice unsupervised feedback handler requires either a query (?q=) to find similar documents.");

        } else {

            uffDocs = expandQueryAndReExecute(rsp, params, maxDocumentsToMatch, flags, q, query, sortSpec,
                    targetFqFilters, mltFqFilters, searcher, mlt, interesting, uffDocs, start, rows);
        }

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

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

    if (interesting != null) {
        addInterestingTerms(rsp, termStyle, interesting);
    }

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

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

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

License:Apache License

private void addDebugInfo(SolrQueryRequest req, SolrQueryResponse rsp, String q, List<Query> mltFqFilters,
        UnsupervisedFeedbackHelper mlt, DocListAndSet mltDocs) {
    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;//  ww w.j av a2 s  .  com
                } 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.getRawUFQuery(),
                    mltDocs.docList, dbgQuery, dbgResults);
            if (null != dbgInfo) {
                if (null != mltFqFilters) {
                    dbgInfo.add("filter_queries", req.getParams().getParams(CommonParams.FQ));
                    List<String> fqs = new ArrayList<String>(mltFqFilters.size());
                    for (Query fq : mltFqFilters) {
                        fqs.add(QueryParsing.toString(fq, req.getSchema()));
                    }
                    dbgInfo.add("mlt_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.dspace.app.xmlui.aspect.discovery.json.JSONSolrSearcher.java

License:BSD License

@Override
public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par)
        throws ProcessingException, SAXException, IOException {
    //Retrieve all the given parameters
    Request request = ObjectModelHelper.getRequest(objectModel);
    this.response = ObjectModelHelper.getResponse(objectModel);

    query = request.getParameter(CommonParams.Q);
    if (query == null) {
        query = "*:*";
    }//from  w  ww. j  a  v a 2 s .  c  om

    //Retrieve all our filter queries
    filterQueries = request.getParameterValues(CommonParams.FQ);

    //Retrieve our facet fields
    facetFields = request.getParameterValues(FacetParams.FACET_FIELD);

    //Retrieve our facet limit (if any)
    if (request.getParameter(FacetParams.FACET_LIMIT) != null) {
        try {
            facetLimit = Integer.parseInt(request.getParameter(FacetParams.FACET_LIMIT));
        } catch (Exception e) {
            //Should an invalid value be supplied use -1
            facetLimit = -1;
        }
    } else {
        facetLimit = -1;
    }

    //Retrieve our sorting value
    facetSort = request.getParameter(FacetParams.FACET_SORT);
    //Make sure we have a valid sorting value
    if (!FacetParams.FACET_SORT_INDEX.equals(facetSort) && !FacetParams.FACET_SORT_COUNT.equals(facetSort)) {
        facetSort = null;
    }

    //Retrieve our facet min count
    facetMinCount = 1;
    try {
        facetMinCount = Integer.parseInt(request.getParameter(FacetParams.FACET_MINCOUNT));
    } catch (Exception e) {
        facetMinCount = 1;
    }
    jsonWrf = request.getParameter("json.wrf");

    //Retrieve our discovery solr path
    ExtendedProperties props = null;
    //Method that will retrieve all the possible configs we have

    props = ExtendedProperties.convertProperties(ConfigurationManager.getProperties());

    InputStream is = null;
    try {
        File config = new File(props.getProperty("dspace.dir") + "/config/dspace-solr-search.cfg");
        if (config.exists()) {
            props.combine(new ExtendedProperties(config.getAbsolutePath()));
        } else {
            is = SolrServiceImpl.class.getResourceAsStream("dspace-solr-search.cfg");
            ExtendedProperties defaults = new ExtendedProperties();
            defaults.load(is);
            props.combine(defaults);
        }
    } catch (Exception e) {
        log.error("Error while retrieving solr url", e);
        e.printStackTrace();
    } finally {
        if (is != null) {
            is.close();
        }
    }

    if (props.getProperty("solr.search.server") != null) {
        this.solrServerUrl = props.getProperty("solr.search.server").toString();
    }

}