Example usage for org.apache.solr.common SolrDocumentList getStart

List of usage examples for org.apache.solr.common SolrDocumentList getStart

Introduction

In this page you can find the example usage for org.apache.solr.common SolrDocumentList getStart.

Prototype

public long getStart() 

Source Link

Usage

From source file:au.org.ala.biocache.dao.SearchDAOImpl.java

License:Open Source License

/**
 * Process the {@see org.apache.solr.client.solrj.response.QueryResponse} from a SOLR search and return
 * a {@link au.org.ala.biocache.dto.SearchResultDTO}
 *
 * @param qr/*from  w  w w  .j  a va 2  s.c o  m*/
 * @param solrQuery
 * @return
 */
private SearchResultDTO processSolrResponse(SearchRequestParams params, QueryResponse qr, SolrQuery solrQuery,
        Class resultClass) {
    SearchResultDTO searchResult = new SearchResultDTO();
    SolrDocumentList sdl = qr.getResults();
    // Iterator it = qr.getResults().iterator() // Use for download
    List<FacetField> facets = qr.getFacetFields();
    List<FacetField> facetDates = qr.getFacetDates();
    Map<String, Integer> facetQueries = qr.getFacetQuery();
    if (facetDates != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Facet dates size: " + facetDates.size());
        }
        facets.addAll(facetDates);
    }

    List<OccurrenceIndex> results = qr.getBeans(resultClass);

    //facet results
    searchResult.setTotalRecords(sdl.getNumFound());
    searchResult.setStartIndex(sdl.getStart());
    searchResult.setPageSize(solrQuery.getRows()); //pageSize
    searchResult.setStatus("OK");
    String[] solrSort = StringUtils.split(solrQuery.getSortField(), " "); // e.g. "taxon_name asc"
    if (logger.isDebugEnabled()) {
        logger.debug("sortField post-split: " + StringUtils.join(solrSort, "|"));
    }
    searchResult.setSort(solrSort[0]); // sortField
    searchResult.setDir(solrSort[1]); // sortDirection
    searchResult.setQuery(params.getUrlParams()); //this needs to be the original URL>>>>
    searchResult.setOccurrences(results);

    List<FacetResultDTO> facetResults = buildFacetResults(facets);

    //all belong to uncertainty range for now
    if (facetQueries != null && !facetQueries.isEmpty()) {
        Map<String, String> rangeMap = rangeBasedFacets.getRangeMap("uncertainty");
        List<FieldResultDTO> fqr = new ArrayList<FieldResultDTO>();
        for (String value : facetQueries.keySet()) {
            if (facetQueries.get(value) > 0)
                fqr.add(new FieldResultDTO(rangeMap.get(value), facetQueries.get(value), value));
        }
        facetResults.add(new FacetResultDTO("uncertainty", fqr));
    }

    //handle all the range based facets
    if (qr.getFacetRanges() != null) {
        for (RangeFacet rfacet : qr.getFacetRanges()) {
            List<FieldResultDTO> fqr = new ArrayList<FieldResultDTO>();
            if (rfacet instanceof Numeric) {
                Numeric nrfacet = (Numeric) rfacet;
                List<RangeFacet.Count> counts = nrfacet.getCounts();
                //handle the before
                if (nrfacet.getBefore().intValue() > 0) {
                    fqr.add(new FieldResultDTO("[* TO "
                            + getUpperRange(nrfacet.getStart().toString(), nrfacet.getGap(), false) + "]",
                            nrfacet.getBefore().intValue()));
                }
                for (RangeFacet.Count count : counts) {
                    String title = getRangeValue(count.getValue(), nrfacet.getGap());
                    fqr.add(new FieldResultDTO(title, count.getCount()));
                }
                //handle the after
                if (nrfacet.getAfter().intValue() > 0) {
                    fqr.add(new FieldResultDTO("[" + nrfacet.getEnd().toString() + " TO *]",
                            nrfacet.getAfter().intValue()));
                }
                facetResults.add(new FacetResultDTO(nrfacet.getName(), fqr));
            }
        }
    }

    //update image URLs
    for (OccurrenceIndex oi : results) {
        updateImageUrls(oi);
    }

    searchResult.setFacetResults(facetResults);
    // The query result is stored in its original format so that all the information
    // returned is available later on if needed
    searchResult.setQr(qr);
    return searchResult;
}

From source file:co.diji.solr.XMLWriter.java

License:Apache License

public final void writeSolrDocumentList(String name, final SolrDocumentList docs, Set<String> fields)
        throws IOException {
    this.writeDocuments(name, new DocumentListInfo() {
        public int getCount() {
            return docs.size();
        }//from  w w w.j  a  v  a  2s . c  o  m

        public Float getMaxScore() {
            return docs.getMaxScore();
        }

        public long getNumFound() {
            return docs.getNumFound();
        }

        public long getStart() {
            return docs.getStart();
        }

        public void writeDocs(boolean includeScore, Set<String> fields) throws IOException {
            for (SolrDocument doc : docs) {
                writeDoc(null, doc, fields, includeScore);
            }
        }
    }, fields);
}

From source file:com.databasepreservation.visualization.utils.SolrUtils.java

public static <T extends Serializable> IndexResult<T> queryResponseToIndexResult(QueryResponse response,
        Class<T> responseClass, List<String> columnNames, Facets facets) throws GenericException {
    final SolrDocumentList docList = response.getResults();
    final List<FacetFieldResult> facetResults = processFacetFields(facets, response.getFacetFields());
    final long offset = docList.getStart();
    final long limit = docList.size();
    final long totalCount = docList.getNumFound();
    final List<T> docs = new ArrayList<T>();

    for (SolrDocument doc : docList) {
        T result;/* w  w  w .  j av a2  s  . c  om*/
        result = solrDocumentTo(responseClass, doc);
        docs.add(result);
    }

    return new IndexResult<T>(offset, limit, totalCount, docs, facetResults);
}

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

License:Open Source License

private static void printResults(SolrDocumentList solrDocumentList) {
    System.out.println("numFound:" + solrDocumentList.getNumFound());
    System.out.println("start:" + solrDocumentList.getStart());
    for (SolrDocument solrDocument : solrDocumentList) {
        System.out.println("**************");
        System.out.println("title:" + solrDocument.getFieldValue("title"));
        System.out.println("description:" + solrDocument.getFieldValue("description"));
        System.out.println("link:" + solrDocument.getFieldValue("link"));
    }//w w w  .  j  a  v a 2s  .c  o m
}

From source file:com.doculibre.constellio.utils.NamedListUtils.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Element toElement(Object value) {
    String elementTag = null;//from  www  .  j a  va 2 s . c om
    String strValue = null;
    Element item = null;
    if (value == null) {
        return null;

    } else if (value instanceof NamedList) {
        NamedList<Object> nl = (NamedList<Object>) value;
        item = newNamedListElement(nl);

    } else if (value instanceof Integer) {
        elementTag = "int";

    } else if (value instanceof String) {
        elementTag = "str";

    } else if (value instanceof Date) {
        elementTag = "date";
        SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        dateParser.setTimeZone(TimeZone.getTimeZone("GMT"));
        strValue = dateParser.format(value);

    } else if (value instanceof Boolean) {
        elementTag = "bool";
        strValue = ((Boolean) value) ? "true" : "false";

    } else if (value instanceof Long) {
        elementTag = "long";

    } else if (value instanceof Float) {
        elementTag = "float";

    } else if (value instanceof Double) {
        elementTag = "double";

    } else if (value instanceof SolrDocumentList) {
        SolrDocumentList documentList = (SolrDocumentList) value;
        item = newListElement((List) value);
        // We want the name to be the first attribute (for Junit)
        item.setAttribute("name", "");
        item.setAttribute("numFound", "" + documentList.getNumFound());
        item.setAttribute("start", "" + documentList.getStart());

    } else if (value instanceof List) {
        item = newListElement((List) value);

    } else if (value instanceof SolrDocument) {
        // Only for unit tests
        item = newSolrDocument((SolrDocument) value);
        nameElement(item, "doc");

    } else if (value instanceof Map) {
        item = newMapElement(((SolrDocument) value).getFieldValuesMap());

    } else {
        throw new RuntimeException("UnsupportedType " + value.getClass().getSimpleName());
    }

    if (item == null) {
        item = new Element(elementTag);
        item.setText(strValue != null ? strValue : String.valueOf(value));

    }
    return item;
}

From source file:com.nridge.ds.solr.SolrResponseBuilder.java

License:Open Source License

@SuppressWarnings("unchecked")
private Document createGroupCollectionDocument(Group aGroup) {
    Logger appLogger = mAppMgr.getLogger(this, "createGroupCollectionDocument");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    Document groupCollectionDocument = createGroupCollection();
    DataBag groupCollectionBag = groupCollectionDocument.getBag();

    String groupName = aGroup.getGroupValue();
    if (StringUtils.isNotEmpty(groupName))
        groupCollectionBag.setValueByName("group_name", groupName);
    SolrDocumentList solrDocumentList = aGroup.getResult();
    if (solrDocumentList != null) {
        groupCollectionBag.setValueByName("offset_start", solrDocumentList.getStart());
        groupCollectionBag.setValueByName("total_count", solrDocumentList.getNumFound());
        Document groupDocument = new Document(Solr.RESPONSE_GROUP_DOCUMENT, createDocumentTable());
        populateDocument(groupDocument, solrDocumentList);
        groupCollectionDocument.addRelationship(groupDocument.getType(), groupDocument);
    }/*w w  w  .  jav  a2s.com*/

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return groupCollectionDocument;
}

From source file:edu.harvard.lib.lcloud.ItemDAO.java

License:Open Source License

/**
 * Returns SearchResults for a given SolrDocumentList. A full results object with an "items" wrapper
 * element around the mods items is used to logically separate pagination, items and facets in the XML
 * @param doc   solr document list to build results
 * @return      the SearchResults object for this solr result
 * @see         SearchResults/* w  ww .j ava 2  s  . c  o m*/
 */

private SearchResults buildFullResults(SolrDocumentList docs) {
    SearchResults results = new SearchResults();
    Pagination pagination = new Pagination();
    pagination.setNumFound(docs.getNumFound());
    pagination.setStart(docs.getStart());
    pagination.setRows(limit);
    //List<ModsType> modsTypes = new ArrayList<ModsType>();
    ItemGroup itemGroup = new ItemGroup();
    List<Item> items = new ArrayList<Item>();
    for (final SolrDocument doc : docs) {
        Item item = new Item();
        ModsType modsType = null;
        try {
            modsType = (new ItemDAO()).getModsType(doc);
        } catch (JAXBException je) {
            log.error(je.getMessage());
            je.printStackTrace();
        }
        //modsTypes.add(modsType);
        //items.add(item);
        item.setModsType(modsType);
        items.add(item);
    }
    //items.setModsType(modsType);
    itemGroup.setItems(items);
    results.setItemGroup(itemGroup);
    results.setPagination(pagination);
    if (facet != null)
        results.setFacet(facet);
    return results;
}

From source file:edu.harvard.lib.lcloud.ItemDAO.java

License:Open Source License

/**
 * Returns SearchResultsSlim for a given SolrDocumentList. A "slimmer" results object without the 
 * "items" wrapper element is created for better transform to json.
 * @param doc   solr document list to build results
 * @return      the SearchResultsSlim object for this solr result
 * @see         SearchResultsSlim//from w  w w  .j  a  va  2s .c o  m
 */

private SearchResultsSlim buildSlimResults(SolrDocumentList docs) {
    SearchResultsSlim results = new SearchResultsSlim();
    Pagination pagination = new Pagination();
    pagination.setNumFound(docs.getNumFound());
    pagination.setStart(docs.getStart());
    pagination.setRows(limit);
    //List<ModsType> modsTypes = new ArrayList<ModsType>();
    List<Item> items = new ArrayList<Item>();
    for (final SolrDocument doc : docs) {
        Item item = new Item();
        ModsType modsType = null;
        try {
            modsType = (new ItemDAO()).getModsType(doc);
        } catch (JAXBException je) {
            log.error(je.getMessage());
            je.printStackTrace();
        }
        item.setModsType(modsType);
        items.add(item);
    }
    results.setItems(items);
    results.setPagination(pagination);
    if (facet != null)
        results.setFacet(facet);
    return results;
}

From source file:edu.harvard.liblab.ecru.rs.ResourceUtils.java

License:Open Source License

public static ResultsList createResultsList(QueryResponse qr, String inputRows, UriInfo req) throws Exception {
    ResultsList rl = new ResultsList();
    URI uri = req.getRequestUri();
    String query = uri.getQuery();

    UriBuilder uriBuild = req.getRequestUriBuilder();
    SolrDocumentList docList = qr.getResults();
    long numFound = docList.getNumFound();
    long start = docList.getStart();
    long rows = 10;
    try {/*from w  w  w . jav  a 2s. co m*/
        if (inputRows != null && !inputRows.trim().isEmpty()) {
            Long r = new Long(inputRows);
            rows = r.longValue();
        }
    } catch (NumberFormatException e) {
        System.err.println("Couldn't convert rows: " + inputRows);
    }

    rl.setItems(convertEcruBeans(qr.getBeans(EcruBase.class), start, uriBuild));

    Summary sum = new Summary(query, numFound, rows, start);

    // Don't bother with faceting if there are no more found than the rows
    if (numFound > rows) {
        Faceting facets = getFaceting(qr.getFacetFields());
        facets = decorateFacets(uriBuild, facets);
        rl.setFaceting(facets);
        // get prev and next, if relevant
        if (start + rows < numFound) {
            sum.setNextUrl(createUrlWithNewParam(uriBuild, "start", (start + rows)));
        }
        if (start - rows > -1) {
            sum.setPrevUrl(createUrlWithNewParam(uriBuild, "start", (start - rows)));
        }
    }
    rl.setSummary(sum);
    return rl;
}

From source file:edu.lternet.pasta.datapackagemanager.solr.search.SimpleSolrSearch.java

License:Apache License

private String solrDocumentListToXML(SolrDocumentList solrDocumentList) {
    String xmlString = "";
    final String INDENT = "    ";
    long numFound = solrDocumentList.getNumFound();
    long start = solrDocumentList.getStart();
    String[] fieldsArray = getFieldList();

    String firstLine = String.format("<resultset numFound='%d' start='%d' rows='%d'>\n", numFound, start, rows);
    StringBuilder sb = new StringBuilder(firstLine);

    for (SolrDocument solrDocument : solrDocumentList) {
        sb.append(String.format("%s<document>\n", INDENT));

        if (fieldsArray != null) {

            for (String fieldName : fieldsArray) {

                String wrapperElement = wrapperElements.get(fieldName);

                if (fieldName.equals("title")) {
                    String title = (String) solrDocument.getFirstValue("title");
                    sb.append(String.format("%s%s<%s>%s</%s>\n", INDENT, INDENT, fieldName, title, fieldName));
                } else if (wrapperElement != null) {
                    sb.append(String.format("%s%s<%s>\n", INDENT, INDENT, wrapperElement));
                    Collection<Object> multiValues = solrDocument.getFieldValues(fieldName);
                    if (multiValues != null && multiValues.size() > 0) {
                        for (Object value : multiValues) {
                            String valueStr = null;
                            if (isDateField(fieldName)) {
                                Date dateValue = (Date) value;
                                dateValue = adjustDate(dateValue);
                                String formatPattern = bestDateFormat(fieldName);
                                SimpleDateFormat sdf = new SimpleDateFormat(formatPattern);
                                if (dateValue != null) {
                                    valueStr = sdf.format(dateValue);
                                }/*from w w w . j  av a2 s  . c  o  m*/
                            } else {
                                valueStr = (String) value;
                            }

                            sb.append(String.format("%s%s%s<%s>%s</%s>\n", INDENT, INDENT, INDENT, fieldName,
                                    valueStr, fieldName));
                        }
                    }
                    sb.append(String.format("%s%s</%s>\n", INDENT, INDENT, wrapperElement));
                } else {
                    String fieldValue = "";
                    if (isDateField(fieldName)) {
                        Date dateValue = (Date) solrDocument.getFieldValue(fieldName);
                        dateValue = adjustDate(dateValue);
                        String formatPattern = bestDateFormat(fieldName);
                        SimpleDateFormat sdf = new SimpleDateFormat(formatPattern);
                        if (dateValue != null) {
                            fieldValue = sdf.format(dateValue);
                        }
                    } else {
                        fieldValue = (String) solrDocument.getFieldValue(fieldName);
                        if (fieldValue == null)
                            fieldValue = "";
                    }
                    sb.append(String.format("%s%s<%s>%s</%s>\n", INDENT, INDENT, fieldName, fieldValue,
                            fieldName));

                    /*
                     * Support the older format for search results.
                     * 
                     * These element names ("docid", "packageId", and "pubDate")
                     * were never officially documented but some clients might rely 
                     * on them. They should be deprecated. They have been
                     * replaced with element names that exactly match their
                     * corresponding Solr field names: "id", "packageid", and "pubdate".
                     */
                    if (fieldName.equals("id")) {
                        sb.append(String.format("%s%s<docid>%s</docid>\n", INDENT, INDENT, fieldValue));
                    } else if (fieldName.equals("packageid")) {
                        sb.append(String.format("%s%s<packageId>%s</packageId>\n", INDENT, INDENT, fieldValue));
                    } else if (fieldName.equals("pubdate")) {
                        sb.append(String.format("%s%s<pubDate>%s</pubDate>\n", INDENT, INDENT, fieldValue));
                    }
                }
            }
        }

        sb.append(String.format("%s</document>\n", INDENT));
    }

    sb.append("</resultset>\n");
    xmlString = sb.toString();

    return xmlString;
}