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

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

Introduction

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

Prototype

String ROWS

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

Click Source Link

Document

number of documents to return starting at "start"

Usage

From source file:org.alfresco.solr.query.AbstractQParser.java

License:Open Source License

@Override
public SortSpec getSortSpec(boolean useGlobalParams) throws SyntaxError {

    getQuery(); // ensure query is parsed first

    String sortStr = null;//from www.  j a  va2 s.  co  m
    String startS = null;
    String rowsS = null;

    if (localParams != null) {
        sortStr = localParams.get(CommonParams.SORT);
        startS = localParams.get(CommonParams.START);
        rowsS = localParams.get(CommonParams.ROWS);

        // if any of these parameters are present, don't go back to the global params
        if (sortStr != null || startS != null || rowsS != null) {
            useGlobalParams = false;
        }
    }

    if (useGlobalParams) {
        if (sortStr == null) {
            sortStr = params.get(CommonParams.SORT);
        }
        if (startS == null) {
            startS = params.get(CommonParams.START);
        }
        if (rowsS == null) {
            rowsS = params.get(CommonParams.ROWS);
        }
    }

    int start = startS != null ? Integer.parseInt(startS) : 0;
    int rows = rowsS != null ? Integer.parseInt(rowsS) : 10;

    // Fix sort fields here
    if (sortStr != null) {
        StringBuilder builder = new StringBuilder();
        StringBuilder propertyBuilder = null;
        char c;
        for (int i = 0; i < sortStr.length(); i++) {
            c = sortStr.charAt(i);
            if (propertyBuilder == null) {
                if (!Character.isWhitespace(c) && (c != ',')) {
                    propertyBuilder = new StringBuilder();
                    propertyBuilder.append(c);
                } else {
                    builder.append(c);
                }
            } else {
                if (Character.isWhitespace(c) || (c == ',')) {
                    String toAppend = AlfrescoSolrDataModel.getInstance()
                            .mapProperty(propertyBuilder.toString(), FieldUse.SORT, getReq());
                    builder.append(toAppend);
                    builder.append(c);
                    propertyBuilder = null;
                } else {
                    propertyBuilder.append(c);
                }
            }
        }
        if (propertyBuilder != null) {
            String toAppend = AlfrescoSolrDataModel.getInstance().mapProperty(propertyBuilder.toString(),
                    FieldUse.SORT, getReq());
            builder.append(toAppend);
        }
        sortStr = builder.toString();
    }

    if (sortStr != null) {
        sortStr = sortStr.replaceAll("^ID(\\s)", "id$1");
        sortStr = sortStr.replaceAll("(\\s)ID(\\s)", "$1id$2");
    }
    SortSpec sort = SortSpecParsing.parseSortSpec(sortStr, req);

    sort.setOffset(start);
    sort.setCount(rows);
    return sort;
}

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

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*  w  w  w. ja  v  a  2 s  . c  o  m*/
public void addFTSStatusCounts(NamedList<Object> report) {
    try (SolrQueryRequest request = newSolrQueryRequest()) {
        ModifiableSolrParams params = new ModifiableSolrParams(request.getParams()).set(CommonParams.Q, "*:*")
                .set(CommonParams.ROWS, 0).set(FacetParams.FACET, true)
                .set(FacetParams.FACET_FIELD, FIELD_FTSSTATUS);

        SolrQueryResponse response = cloud.getResponse(nativeRequestHandler, request, params);
        NamedList facetCounts = (NamedList) response.getValues().get("facet_counts");
        NamedList facetFields = (NamedList) facetCounts.get("facet_fields");
        NamedList<Integer> ftsStatusCounts = (NamedList) facetFields.get(FIELD_FTSSTATUS);

        long cleanCount = this.getSafeCount(ftsStatusCounts, FTSStatus.Clean.toString());
        report.add("Node count with FTSStatus Clean", cleanCount);

        long dirtyCount = this.getSafeCount(ftsStatusCounts, FTSStatus.Dirty.toString());
        report.add("Node count with FTSStatus Dirty", dirtyCount);

        long newCount = this.getSafeCount(ftsStatusCounts, FTSStatus.New.toString());
        report.add("Node count with FTSStatus New", newCount);
    }
}

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

License:Open Source License

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

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

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

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

License:Open Source License

private long topNodeId(String sortDir) {
    try (SolrQueryRequest request = this.newSolrQueryRequest()) {
        ModifiableSolrParams params = new ModifiableSolrParams(request.getParams())
                .set(CommonParams.Q, FIELD_DOC_TYPE + ":" + DOC_TYPE_NODE).set(CommonParams.ROWS, 1)
                .set(CommonParams.SORT, FIELD_DBID + " " + sortDir).set(CommonParams.FL, FIELD_DBID);

        SolrDocumentList docs = cloud.getSolrDocumentList(nativeRequestHandler, request, params);
        return docs.stream().findFirst().map(doc -> getFieldValueLong(doc, FIELD_DBID)).orElse(0L);
    }/*  www  . j a v a  2 s  .  c  o  m*/
}

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

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
private NamedList<Integer> getFacets(SolrQueryRequest request, String query, String field, int minCount) {
    ModifiableSolrParams params = new ModifiableSolrParams(request.getParams()).set(CommonParams.Q, query)
            .set(CommonParams.ROWS, 0).set(FacetParams.FACET, true).set(FacetParams.FACET_FIELD, field)
            .set(FacetParams.FACET_MINCOUNT, minCount);

    SolrQueryResponse response = cloud.getResponse(nativeRequestHandler, request, params);
    NamedList facetCounts = (NamedList) response.getValues().get("facet_counts");
    NamedList facetFields = (NamedList) facetCounts.get("facet_fields");
    return (NamedList) facetFields.get(field);
}

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

License:Open Source License

private int getDocListSize(String query) {
    try (SolrQueryRequest request = this.newSolrQueryRequest()) {
        ModifiableSolrParams params = new ModifiableSolrParams(request.getParams()).set(CommonParams.Q, query)
                .set(CommonParams.ROWS, 0);
        ResultContext resultContext = cloud.getResultContext(nativeRequestHandler, request, params);
        return resultContext.getDocList().matches();
    }//from   www . java 2 s.  c  om
}

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.//from  w ww.  ja v a2 s.c  o  m
 */
@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.apache.gora.solr.query.SolrResult.java

License:Apache License

public SolrResult(DataStore<K, T> dataStore, Query<K, T> query, SolrServer server, int resultsSize)
        throws IOException {
    super(dataStore, query);
    store = (SolrStore<K, T>) dataStore;
    ModifiableSolrParams params = new ModifiableSolrParams();
    if (query instanceof PartitionQueryImpl) {
        query = ((PartitionQueryImpl<K, T>) query).getBaseQuery();
    }//from   w w w. j a  v  a2 s. c  o  m
    String q = ((SolrQuery<K, T>) query).toSolrQuery();
    params.set(CommonParams.Q, q);
    fields = query.getFields();
    if (fields == null) {
        params.set(CommonParams.FL, "*");
    } else {
        HashSet<String> uniqFields = new HashSet<String>(Arrays.asList(fields));
        String keyFld = ((SolrStore<K, T>) dataStore).getMapping().getPrimaryKey();
        uniqFields.add(keyFld); // return also primary key
        StringBuilder sb = new StringBuilder();
        for (String f : uniqFields) {
            if (sb.length() > 0)
                sb.append(',');
            sb.append(f);
        }
        params.set(CommonParams.FL, sb.toString());
    }
    params.set(CommonParams.ROWS, resultsSize);
    try {
        QueryResponse rsp = server.query(params);
        list = rsp.getResults();
    } catch (SolrServerException e) {
        e.printStackTrace();
        throw new IOException(e);
    }
}

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  www.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);
    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 .java2 s  . co m
    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);
}