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:eu.europeana.core.querymodel.query.DocIdWindowPagerImpl.java

License:EUPL

@Override
@SuppressWarnings({ "AccessingNonPublicFieldOfAnotherObject" })
public void initialize(Map<String, String[]> httpParameters, BreadcrumbFactory breadcrumbFactory, Locale locale,
        SolrQuery originalBriefSolrQuery, QueryModelFactory queryModelFactory, RecordDefinition metadataModel)
        throws SolrServerException, EuropeanaQueryException {
    this.query = originalBriefSolrQuery.getQuery();
    int fullDocUriInt = getFullDocInt(httpParameters, originalBriefSolrQuery);
    this.fullDocUriInt = fullDocUriInt;
    int solrStartRow = getSolrStart(fullDocUriInt);
    QueryResponse queryResponse = queryModelFactory.getPagingQueryResponse(originalBriefSolrQuery,
            httpParameters, solrStartRow);
    if (queryResponse.getResults() == null) {
        throw new EuropeanaQueryException("no results for this query"); // if no results are found return null to signify that docIdPage can be created.
    } else if (queryResponse.getResults().size() == 0) {
        throw new EuropeanaQueryException("no results for this query"); // if no results are found return null to signify that docIdPage can be created.
    }/*from   ww w.j  av  a  2 s  . c om*/
    List<? extends DocId> list = SolrBindingService.getDocIds(queryResponse);
    final SolrDocumentList response = queryResponse.getResults();
    this.breadcrumbs = breadcrumbFactory.createList(originalBriefSolrQuery, locale); // todo comment out
    int offset = (int) response.getStart();
    int numFound = (int) response.getNumFound();
    this.numFound = numFound;
    setNextAndPrevious(fullDocUriInt, list, offset, numFound);
    this.docIdWindow = new DocIdWindowImpl(list, offset, numFound);
    if (this.hasNext) {
        this.setNextFullDocUrl(httpParameters);
    }
    if (this.hasPrevious) {
        this.setPreviousFullDocUrl(httpParameters);
    }
}

From source file:net.cloudfree.apps.shop.internal.app.ListingServlet.java

License:Open Source License

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final IListingManager manager = ModelUtil.getManager(IListingManager.class, getContext());

    final ISolrQueryExecutor queryExecutor = (ISolrQueryExecutor) manager.getAdapter(ISolrQueryExecutor.class);
    if (null == queryExecutor) {
        resp.sendError(404);// ww w .  j a v  a2  s .c  o m
        return;
    }

    final List<String> selectedFacets = new ArrayList<String>();

    final SolrQuery query = new SolrQuery();
    boolean facet = true;
    boolean checkVariations = false;

    final String path = req.getPathInfo();
    if ((null != path) && (path.length() > 1)) {
        query.setFilterQueries(Document.URI_PATH + ":" + path.substring(1));
        query.setFields("id", "title", "price", "name", "score", "img480", "uripath", "description");
        facet = false;
        checkVariations = true;
    } else {
        final String q = req.getParameter("q");
        if (StringUtils.isNotBlank(q)) {
            query.setQuery(q);
        }

        query.setFields("id", "title", "price", "name", "score", "img48", "uripath");

        // ignore variations
        final String f = req.getParameter("f");
        if (StringUtils.isNotBlank(f)) {
            query.addFilterQuery(f);
        } else {
            query.addFilterQuery("-type:variation");
        }

        // facet narrowing?
        final String[] narrows = req.getParameterValues("narrow");
        if (null != narrows) {
            for (final String narrow : narrows) {
                if (StringUtils.isBlank(narrow)) {
                    continue;
                }
                final String[] split = StringUtils.split(narrow, ':');
                if (split.length != 2) {
                    continue;
                }
                final String name = split[0];
                final String value = split[1];
                if (StringUtils.isBlank(name) || StringUtils.isBlank(value)) {
                    continue;
                }
                final FacetFilter filter = facetFilters.get(name);
                if (null != filter) {
                    if (filter.addFilter(query, value)) {
                        selectedFacets.add(name + ":" + value);
                    }
                }
            }
        }
    }

    query.setQueryType("dismax");
    query.set("debug", true);

    // facet fields
    if (facet) {
        query.setFacet(true);
        for (final FacetFilter filter : facetFilters.values()) {
            filter.defineFilter(query);
        }
    }

    final QueryResponse response = queryExecutor.query(query);
    final SolrDocumentList results = response.getResults();

    resp.setContentType("text/html");
    resp.setCharacterEncoding("UTF-8");

    final PrintWriter writer = resp.getWriter();

    writer.println("<html><head>");
    writer.println("<title>");
    writer.println(path);
    writer.println(" - Shop Listings</title>");
    writer.println("</head><body>");

    writer.println("<h1>Found Listings</h1>");
    writer.println("<p>");
    writer.println("CloudFree found <strong>" + results.getNumFound() + "</strong> products in "
            + (response.getQTime() < 1000 ? "less than a second." : (response.getQTime() + "ms.")));
    if (results.size() < results.getNumFound()) {
        writer.println("<br/>");
        if (results.getStart() == 0) {
            writer.println("Only the first " + results.size() + " products are shown.");
        } else {
            writer.println("Only products " + results.getStart() + " till "
                    + (results.getStart() + results.size()) + " will be shown.");
        }
    }
    writer.println("</p>");

    final List<FacetField> facetFields = response.getFacetFields();
    if ((null != facetFields) && !facetFields.isEmpty()) {
        writer.println("<p>");
        writer.println("You can filter the results by: </br>");
        for (final FacetField facetField : facetFields) {
            final List<Count> values = facetField.getValues();
            if ((null != values) && !values.isEmpty()) {
                writer.println("<div style=\"float:left;\">");
                writer.print("<em>");
                writer.print(facetField.getName());
                writer.print("</em>");
                writer.println("<ul style=\"margin:0;\">");
                int filters = 0;
                for (final Count count : values) {
                    if (count.getCount() == 0) {
                        continue;
                    }
                    writer.print("<li>");
                    writer.print(count.getName());
                    writer.print(" (");
                    writer.print(count.getCount());
                    writer.print(")");
                    writer.print("</li>");
                    filters++;
                }
                if (filters == 0) {
                    writer.print("<li>none</li>");
                }
                writer.println("</ul>");
                writer.println("</div>");
            }
        }
        writer.println("<div style=\"clear:both;\">&nbsp;</div>");
        writer.println("</p>");
    }

    writer.println("<p>");
    if (!results.isEmpty()) {
        for (final SolrDocument listing : results) {
            writeListing(listing, writer, req);

            if (checkVariations) {
                final SolrQuery query2 = new SolrQuery();
                query2.setQuery("parentid:" + listing.getFirstValue("id"));
                query2.setFields("id", "title", "price", "name", "score", "img48", "uripath", "color", "size");
                final QueryResponse response2 = queryExecutor.query(query2);
                final SolrDocumentList results2 = response2.getResults();
                if ((null != results2) && !results2.isEmpty()) {
                    writer.println("There are " + results2.size() + " variations available.");
                    for (final SolrDocument variation : results2) {
                        writeListing(variation, writer, req);
                    }
                }
            }
        }
    } else {
        writer.println("No listings found!");
    }
    writer.println("</p>");
    writer.println("</body>");

}

From source file:net.hasor.search.server.rsf.service.SorlSearchService.java

License:Apache License

@Override
public QuerySearchResult query(SearchQuery searchQuery) throws Throwable {
    SolrQuery solrQuery = new SolrQuery();
    solrQuery.add(new MultiMapSolrParams(searchQuery.toMap()));
    QueryResponse response = getSolrClient().query(solrQuery);
    SolrDocumentList docList = response.getResults();
    ///*  ww w. j  a  v  a2 s .co m*/
    List<SearchDocument> documentList = new ArrayList<SearchDocument>();
    if (docList != null) {
        for (SolrDocument solrDocument : docList) {
            SearchDocument document = convetTo(solrDocument);
            documentList.add(document);
        }
    }
    //
    QuerySearchResult searchResult = new QuerySearchResult(documentList);
    searchResult.setElapsedTime(response.getElapsedTime());
    searchResult.setMaxScore(docList.getMaxScore());
    searchResult.setNumFound(docList.getNumFound());
    searchResult.setStart(docList.getStart());
    searchResult.setStatus(response.getStatus());
    searchResult.setQueryTime(response.getQTime());
    return searchResult;
}

From source file:net.yacy.cora.federate.solr.responsewriter.EnhancedXMLResponseWriter.java

License:Open Source License

private static final void writeDocs(final Writer writer,
        @SuppressWarnings("unused") final SolrQueryRequest request, final SolrDocumentList docs)
        throws IOException {
    boolean includeScore = false;
    final int sz = docs.size();
    writer.write("<result");
    writeAttr(writer, "name", "response");
    writeAttr(writer, "numFound", Long.toString(docs.getNumFound()));
    writeAttr(writer, "start", Long.toString(docs.getStart()));
    if (includeScore) {
        writeAttr(writer, "maxScore", Float.toString(docs.getMaxScore()));
    }/*from www. ja  v  a2s.c om*/
    if (sz == 0) {
        writer.write("/>");
        return;
    }
    writer.write('>');
    writer.write(lb);
    Iterator<SolrDocument> iterator = docs.iterator();
    for (int i = 0; i < sz; i++) {
        SolrDocument doc = iterator.next();
        writeDoc(writer, doc);
    }
    writer.write("</result>");
    writer.write(lb);
}

From source file:org.ala.dao.FulltextSearchDaoImplSolr.java

License:Open Source License

/**
 * Re-usable method for performing SOLR searches - takes SolrQuery input
 *
 * @param solrQuery/* w w  w .  j a va  2  s . c o  m*/
 * @param filterQuery
 * @param pageSize
 * @param startIndex
 * @param sortField
 * @param sortDirection
 * @return
 * @throws SolrServerException
 */
private SearchResultsDTO doSolrQuery(SolrQuery solrQuery, String[] filterQuery, Integer pageSize,
        Integer startIndex, String sortField, String sortDirection) throws Exception {
    SearchResultsDTO searchResults = new SearchResultsDTO();
    QueryResponse qr = getSolrQueryResponse(solrQuery, filterQuery, pageSize, startIndex, sortField,
            sortDirection);

    //process results
    SolrDocumentList sdl = qr.getResults();
    List<FacetField> facets = qr.getFacetFields();
    List<SearchDTO> results = new ArrayList<SearchDTO>();
    List<FacetResultDTO> facetResults = new ArrayList<FacetResultDTO>();
    searchResults.setTotalRecords(sdl.getNumFound());
    searchResults.setStartIndex(sdl.getStart());
    searchResults.setPageSize(pageSize);
    searchResults.setStatus("OK");
    searchResults.setSort(sortField);
    searchResults.setDir(sortDirection);
    searchResults.setQuery(solrQuery.getQuery());
    // populate SOLR search results
    if (!sdl.isEmpty()) {
        for (SolrDocument doc : sdl) {
            if (IndexedTypes.TAXON.toString().equalsIgnoreCase((String) doc.getFieldValue("idxtype"))) {
                results.add(createTaxonConceptFromIndex(qr, doc));
            } else if (IndexedTypes.COLLECTION.toString()
                    .equalsIgnoreCase((String) doc.getFieldValue("idxtype"))) {
                results.add(createCollectionFromIndex(qr, doc));
            } else if (IndexedTypes.INSTITUTION.toString()
                    .equalsIgnoreCase((String) doc.getFieldValue("idxtype"))) {
                results.add(createInstitutionFromIndex(qr, doc));
            } else if (IndexedTypes.DATAPROVIDER.toString()
                    .equalsIgnoreCase((String) doc.getFieldValue("idxtype"))) {
                results.add(createDataProviderFromIndex(qr, doc));
            } else if (IndexedTypes.DATASET.toString()
                    .equalsIgnoreCase((String) doc.getFieldValue("idxtype"))) {
                results.add(createDatasetFromIndex(qr, doc));
            } else if (IndexedTypes.REGION.toString().equalsIgnoreCase((String) doc.getFieldValue("idxtype"))) {
                results.add(createRegionFromIndex(qr, doc));
            } else if (IndexedTypes.WORDPRESS.toString()
                    .equalsIgnoreCase((String) doc.getFieldValue("idxtype"))) {
                results.add(createWordpressFromIndex(qr, doc));
            } else if (IndexedTypes.LAYERS.toString().equalsIgnoreCase((String) doc.getFieldValue("idxtype"))) {
                results.add(createLayerFromIndex(qr, doc));
            } else {
                results.add(createSearchDTOFromIndex(qr, doc));
            }
        }
    } else {
        logger.debug("No results for query.");
    }
    searchResults.setResults(results);
    // populate SOLR facet results
    if (facets != null) {
        for (FacetField facet : facets) {
            List<FacetField.Count> facetEntries = facet.getValues();
            if ((facetEntries != null) && (facetEntries.size() > 0)) {
                ArrayList<FieldResultDTO> r = new ArrayList<FieldResultDTO>();
                for (FacetField.Count fcount : facetEntries) {
                    r.add(new FieldResultDTO(fcount.getName(), fcount.getCount()));
                }
                FacetResultDTO fr = new FacetResultDTO(facet.getName(), r);
                facetResults.add(fr);
            }
        }
    }
    searchResults.setFacetResults(facetResults);
    // The query result is stored in its original format so that all the information
    // returned is available later on if needed
    searchResults.setQr(qr);
    return searchResults;
}

From source file:org.ambraproject.search.service.SolrSearchService.java

License:Apache License

private SearchResultSinglePage readQueryResults(QueryResponse queryResponse, SolrQuery query) {
    SolrDocumentList documentList = queryResponse.getResults();

    if (log.isInfoEnabled()) {
        StringBuilder filterQueriesForLog = new StringBuilder();
        if (query.getFilterQueries() != null && query.getFilterQueries().length > 0) {
            for (String filterQuery : query.getFilterQueries()) {
                filterQueriesForLog.append(filterQuery).append(" , ");
            }/*from  w w w . j  a  v  a 2 s .co  m*/
            if (filterQueriesForLog.length() > 3) {
                filterQueriesForLog.replace(filterQueriesForLog.length() - 3, filterQueriesForLog.length(), "");
            } else {
                filterQueriesForLog.append("No Filter Queries");
            }
        }

        log.info("query.getQuery():{ " + query.getQuery() + " }" + ", query.getSortFields():{ "
                + (query.getSortFields() == null ? null : Arrays.asList(query.getSortFields())) + " }"
                + ", query.getFilterQueries():{ " + filterQueriesForLog.toString() + " }" + ", found:"
                + documentList.getNumFound() + ", start:" + documentList.getStart() + ", max_score:"
                + documentList.getMaxScore() + ", QTime:" + queryResponse.getQTime() + "ms");

        // TODO: implement spell-checking in a meaningful manner.  This loop exists only to generate log output.
        // TODO: Add "spellcheckAlternatives" or something like it to the SearchHits class so it can be displayed to the user like Google's "did you mean..."
        // TODO: Turn off spellchecking for the "author" field.
        if (queryResponse.getSpellCheckResponse() != null
                && queryResponse.getSpellCheckResponse().getSuggestionMap() != null
                && queryResponse.getSpellCheckResponse().getSuggestionMap().keySet().size() > 0) {
            StringBuilder sb = new StringBuilder("Spellcheck alternative suggestions:");
            for (String token : queryResponse.getSpellCheckResponse().getSuggestionMap().keySet()) {
                sb.append(" { ").append(token).append(" : ");
                if (queryResponse.getSpellCheckResponse().getSuggestionMap().get(token).getAlternatives()
                        .size() < 1) {
                    sb.append("NO ALTERNATIVES");
                } else {
                    for (String alternative : queryResponse.getSpellCheckResponse().getSuggestionMap()
                            .get(token).getAlternatives()) {
                        sb.append(alternative).append(", ");
                    }
                    sb.replace(sb.length() - 2, sb.length(), ""); // Remove last comma and space.
                }
                sb.append(" } ,");
            }
            log.info(sb.replace(sb.length() - 2, sb.length(), "").toString()); // Remove last comma and space.
        } else {
            log.info("Solr thinks everything in the query is spelled correctly.");
        }
    }

    Map<String, Map<String, List<String>>> highlightings = queryResponse.getHighlighting();

    List<SearchHit> searchResults = new ArrayList<SearchHit>();
    for (SolrDocument document : documentList) {

        String id = getFieldValue(document, "id", String.class, query.toString());
        String message = id == null ? query.toString() : id;
        Float score = getFieldValue(document, "score", Float.class, message);
        String title = getFieldValue(document, "title_display", String.class, message);
        Date publicationDate = getFieldValue(document, "publication_date", Date.class, message);
        String eissn = getFieldValue(document, "eissn", String.class, message);
        String journal = getFieldValue(document, "journal", String.class, message);
        String articleType = getFieldValue(document, "article_type", String.class, message);

        List<String> authorList = getFieldMultiValue(document, message, String.class, "author_display");

        String highlights = null;
        if (query.getHighlight()) {
            highlights = getHighlights(highlightings.get(id));
        }

        SearchHit hit = new SearchHit(score, id, title, highlights, authorList, publicationDate, eissn, journal,
                articleType);

        if (log.isDebugEnabled())
            log.debug(hit.toString());

        searchResults.add(hit);
    }

    //here we assume that number of hits is always going to be withing range of int
    SearchResultSinglePage results = new SearchResultSinglePage((int) documentList.getNumFound(), -1,
            searchResults, query.getQuery());

    if (queryResponse.getFacetField("subject_facet") != null) {
        results.setSubjectFacet(facetCountsToHashMap(queryResponse.getFacetField("subject_facet")));
    }

    if (queryResponse.getFacetField("author_facet") != null) {
        results.setAuthorFacet(facetCountsToHashMap(queryResponse.getFacetField("author_facet")));
    }

    if (queryResponse.getFacetField("editor_facet") != null) {
        results.setEditorFacet(facetCountsToHashMap(queryResponse.getFacetField("editor_facet")));
    }

    if (queryResponse.getFacetField("article_type_facet") != null) {
        results.setArticleTypeFacet(facetCountsToHashMap(queryResponse.getFacetField("article_type_facet")));
    }

    if (queryResponse.getFacetField("affiliate_facet") != null) {
        results.setInstitutionFacet(facetCountsToHashMap(queryResponse.getFacetField("affiliate_facet")));
    }

    if (queryResponse.getFacetField("cross_published_journal_key") != null) {
        results.setJournalFacet(
                facetCountsToHashMap(queryResponse.getFacetField("cross_published_journal_key")));
    }

    return results;
}

From source file:org.ambraproject.service.search.SolrSearchService.java

License:Apache License

@SuppressWarnings("unchecked")
private SearchResultSinglePage readQueryResults(QueryResponse queryResponse, SolrQuery query) {
    SolrDocumentList documentList = queryResponse.getResults();

    if (log.isInfoEnabled()) {
        StringBuilder filterQueriesForLog = new StringBuilder();
        if (query.getFilterQueries() != null && query.getFilterQueries().length > 0) {
            for (String filterQuery : query.getFilterQueries()) {
                filterQueriesForLog.append(filterQuery).append(" , ");
            }/* w  w  w  .ja v  a 2s.c  o m*/
            if (filterQueriesForLog.length() > 3) {
                filterQueriesForLog.replace(filterQueriesForLog.length() - 3, filterQueriesForLog.length(), "");
            } else {
                filterQueriesForLog.append("No Filter Queries");
            }
        }

        log.info("query.getQuery():{ " + query.getQuery() + " }" + ", query.getSortFields():{ "
                + (query.getSortFields() == null ? null : Arrays.asList(query.getSortFields())) + " }"
                + ", query.getFilterQueries():{ " + filterQueriesForLog.toString() + " }" + ", found:"
                + documentList.getNumFound() + ", start:" + documentList.getStart() + ", max_score:"
                + documentList.getMaxScore() + ", QTime:" + queryResponse.getQTime() + "ms");

        // TODO: implement spell-checking in a meaningful manner.  This loop exists only to generate log output.
        // TODO: Add "spellcheckAlternatives" or something like it to the SearchHits class so it can be displayed to the user like Google's "did you mean..."
        // TODO: Turn off spellchecking for the "author" field.
        if (queryResponse.getSpellCheckResponse() != null
                && queryResponse.getSpellCheckResponse().getSuggestionMap() != null
                && queryResponse.getSpellCheckResponse().getSuggestionMap().keySet().size() > 0) {
            StringBuilder sb = new StringBuilder("Spellcheck alternative suggestions:");
            for (String token : queryResponse.getSpellCheckResponse().getSuggestionMap().keySet()) {
                sb.append(" { ").append(token).append(" : ");
                if (queryResponse.getSpellCheckResponse().getSuggestionMap().get(token).getAlternatives()
                        .size() < 1) {
                    sb.append("NO ALTERNATIVES");
                } else {
                    for (String alternative : queryResponse.getSpellCheckResponse().getSuggestionMap()
                            .get(token).getAlternatives()) {
                        sb.append(alternative).append(", ");
                    }
                    sb.replace(sb.length() - 2, sb.length(), ""); // Remove last comma and space.
                }
                sb.append(" } ,");
            }
            log.info(sb.replace(sb.length() - 2, sb.length(), "").toString()); // Remove last comma and space.
        } else {
            log.info("Solr thinks everything in the query is spelled correctly.");
        }
    }

    List<SearchHit> searchResults = new ArrayList<SearchHit>();
    for (SolrDocument document : documentList) {

        String id = SolrServiceUtil.getFieldValue(document, "id", String.class, query.toString());
        String message = id == null ? query.toString() : id;
        Float score = SolrServiceUtil.getFieldValue(document, "score", Float.class, message);
        String title = SolrServiceUtil.getFieldValue(document, "title_display", String.class, message);
        Date publicationDate = SolrServiceUtil.getFieldValue(document, "publication_date", Date.class, message);
        String eissn = SolrServiceUtil.getFieldValue(document, "eissn", String.class, message);
        String journal = SolrServiceUtil.getFieldValue(document, "journal", String.class, message);
        String articleType = SolrServiceUtil.getFieldValue(document, "article_type", String.class, message);
        String strikingImage = SolrServiceUtil.getFieldValue(document, "striking_image", String.class, message);
        List<String> abstractText = SolrServiceUtil.getFieldMultiValue(document, "abstract", String.class,
                message);
        List<String> abstractPrimary = SolrServiceUtil.getFieldMultiValue(document, "abstract_primary_display",
                String.class, message);
        List<String> authorList = SolrServiceUtil.getFieldMultiValue(document, "author_display", String.class,
                message);
        // TODO create a dedicated field for checking the existence of assets for a given article.
        List<String> figureTableCaptions = SolrServiceUtil.getFieldMultiValue(document, "figure_table_caption",
                String.class, message);
        List<String> subjects = SolrServiceUtil.getFieldMultiValue(document, "subject", String.class, message);
        List<String> expressionOfconcern = SolrServiceUtil.getFieldMultiValue(document, "expression_of_concern",
                String.class, message);
        String retraction = SolrServiceUtil.getFieldValue(document, "retraction", String.class, message);
        String abstractResult = "";

        //Use the primary abstract if it exists
        if (abstractPrimary.size() > 0) {
            abstractResult = StringUtils.join(abstractPrimary, ", ");
        } else {
            if (abstractText.size() > 0) {
                abstractResult = StringUtils.join(abstractText, ", ");
            }
        }

        //Flatten the list of subjects to a unique set
        Set<String> flattenedSubjects = new HashSet<String>();
        for (String subject : subjects) {
            for (String temp : subject.split("/")) {
                if (temp.trim().length() > 0) {
                    flattenedSubjects.add(temp);
                }
            }
        }

        SearchHit hit = SearchHit.builder().setHitScore(score).setUri(id).setTitle(title)
                .setListOfCreators(authorList).setDate(publicationDate).setIssn(eissn).setJournalTitle(journal)
                .setArticleTypeForDisplay(articleType).setAbstractText(abstractResult)
                .setStrikingImage(strikingImage).setHasAssets(figureTableCaptions.size() > 0)
                .setSubjects(flattenedSubjects).setSubjectsPolyhierarchy(subjects)
                .setExpressionOfConcern(expressionOfconcern).setRetraction(retraction).build();

        if (log.isDebugEnabled())
            log.debug(hit.toString());

        searchResults.add(hit);
    }

    //here we assume that number of hits is always going to be withing range of int
    SearchResultSinglePage results = new SearchResultSinglePage((int) documentList.getNumFound(), -1,
            searchResults, query.getQuery());

    if (queryResponse.getFacetField("subject_facet") != null) {
        List<Map> subjects = facetCountsToHashMap(queryResponse.getFacetField("subject_facet"));

        if (subjects != null) {
            List<Map> subjectResult = new ArrayList<Map>();
            SortedMap<String, Long> topSubjects = null;

            try {
                topSubjects = getTopSubjects();
            } catch (ApplicationException ex) {
                throw new RuntimeException(ex.getMessage(), ex);
            }

            //Remove top level 1 subjects from list, FEND-805
            for (Map<String, Object> m : subjects) {
                if (!topSubjects.containsKey(m.get("name"))) {
                    HashMap<String, Object> hm = new HashMap<String, Object>();
                    hm.put("name", m.get("name"));
                    hm.put("count", m.get("count"));
                    subjectResult.add(hm);
                }
            }

            results.setSubjectFacet(subjectResult);
        } else {
            results.setSubjectFacet(null);
        }
    }

    if (queryResponse.getFacetField("author_facet") != null) {
        results.setAuthorFacet(facetCountsToHashMap(queryResponse.getFacetField("author_facet")));
    }

    if (queryResponse.getFacetField("editor_facet") != null) {
        results.setEditorFacet(facetCountsToHashMap(queryResponse.getFacetField("editor_facet")));
    }

    if (queryResponse.getFacetField("article_type_facet") != null) {
        results.setArticleTypeFacet(facetCountsToHashMap(queryResponse.getFacetField("article_type_facet")));
    }

    if (queryResponse.getFacetField("affiliate_facet") != null) {
        results.setInstitutionFacet(facetCountsToHashMap(queryResponse.getFacetField("affiliate_facet")));
    }

    if (queryResponse.getFacetField("cross_published_journal_key") != null) {
        results.setJournalFacet(
                facetCountsToHashMap(queryResponse.getFacetField("cross_published_journal_key")));
    }

    return results;
}

From source file:org.apache.ranger.solr.SolrAccessAuditsService.java

License:Apache License

public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) {

    // Make call to Solr
    SolrClient solrClient = solrMgr.getSolrClient();

    if (solrClient == null) {
        logger.warn("Solr client is null, so not running the query.");
        throw restErrorUtil.createRESTException("Error connecting to search engine", MessageEnums.ERROR_SYSTEM);
    }//  w  ww  . j  a  v  a 2s  .c  o  m

    VXAccessAuditList returnList = new VXAccessAuditList();
    List<VXAccessAudit> xAccessAuditList = new ArrayList<VXAccessAudit>();

    QueryResponse response = solrUtil.searchResources(searchCriteria, searchFields, sortFields, solrClient);
    if (response == null) {
        logger.warn("Error running search query. searchCriteria=" + searchCriteria.toString());
        throw restErrorUtil.createRESTException("Error running search query", MessageEnums.ERROR_SYSTEM);
    }
    SolrDocumentList docs = response.getResults();
    int i;
    for (i = 0; i < docs.size(); i++) {
        SolrDocument doc = docs.get(i);

        VXAccessAudit vXAccessAudit = populateViewBean(doc);
        xAccessAuditList.add(vXAccessAudit);
    }

    returnList.setPageSize(searchCriteria.getMaxRows());
    returnList.setResultSize(i);
    returnList.setTotalCount((int) docs.getNumFound());
    returnList.setStartIndex((int) docs.getStart());
    returnList.setVXAccessAudits(xAccessAuditList);
    return returnList;
}

From source file:org.codelibs.elasticsearch.solr.solr.XMLWriter.java

License:Apache License

public final void writeSolrDocumentList(final String name, final SolrDocumentList docs,
        final Set<String> fields) throws IOException {
    writeDocuments(name, new DocumentListInfo() {
        @Override/*from w w w .  ja va 2 s .  c  om*/
        public int getCount() {
            return docs.size();
        }

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

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

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

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

From source file:org.codelibs.fess.util.QueryResponseList.java

License:Apache License

public void init(final QueryResponse queryResponse, final int pageSize) {
    long start = 0;
    long numFound = 0;
    if (queryResponse != null) {
        final SolrDocumentList sdList = queryResponse.getResults();
        start = sdList.getStart();
        numFound = sdList.getNumFound();
        queryTime = queryResponse.getQTime();
        searchTime = queryResponse.getElapsedTime();

        final Object partialResultsValue = queryResponse.getResponseHeader().get(PARTIAL_RESULTS);
        if (partialResultsValue != null && ((Boolean) partialResultsValue).booleanValue()) {
            partialResults = true;/*from  w w  w  .j  a va  2 s  .co  m*/
        }

        // build highlighting fields
        final QueryHelper queryHelper = ComponentUtil.getQueryHelper();
        final FieldHelper fieldHelper = ComponentUtil.getFieldHelper();
        final String hlPrefix = queryHelper.getHighlightingPrefix();
        for (final SolrDocument solrDocMap : sdList) {
            final Map<String, Object> docMap = new HashMap<String, Object>();
            docMap.putAll(solrDocMap);

            try {
                final Object idValue = docMap.get(fieldHelper.idField);
                if (queryResponse.getHighlighting().get(idValue) != null) {
                    for (final String hf : queryHelper.getHighlightingFields()) {
                        final List<String> highlightSnippets = queryResponse.getHighlighting().get(idValue)
                                .get(hf);
                        String value = null;
                        if (highlightSnippets != null && !highlightSnippets.isEmpty()) {
                            value = StringUtils.join(highlightSnippets, "...");
                            docMap.put(hlPrefix + hf, value);
                        }
                    }
                }
            } catch (final Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Could not create a highlighting value: " + docMap, e);
                }
            }

            // ContentTitle
            final ViewHelper viewHelper = ComponentUtil.getViewHelper();
            if (viewHelper != null) {
                docMap.put("contentTitle", viewHelper.getContentTitle(docMap));
                docMap.put("contentDescription", viewHelper.getContentDescription(docMap));
                docMap.put("urlLink", viewHelper.getUrlLink(docMap));
                docMap.put("sitePath", viewHelper.getSitePath(docMap));
            }

            parent.add(docMap);
        }

        // facet
        final List<FacetField> facetFields = queryResponse.getFacetFields();
        final Map<String, Integer> facetQueryMap = queryResponse.getFacetQuery();
        if (facetFields != null || facetQueryMap != null) {
            facetResponse = new FacetResponse(facetFields, facetQueryMap);
        }

        // mlt
        final Object moreLikeThisMap = queryResponse.getResponse().get(MORE_LIKE_THIS);
        if (moreLikeThisMap instanceof SimpleOrderedMap) {
            moreLikeThisResponse = new MoreLikeThisResponse();
            final int size = ((SimpleOrderedMap<?>) moreLikeThisMap).size();
            for (int i = 0; i < size; i++) {
                final String id = ((SimpleOrderedMap<?>) moreLikeThisMap).getName(i);
                final Object docList = ((SimpleOrderedMap<?>) moreLikeThisMap).getVal(i);
                if (StringUtil.isNotBlank(id) && docList instanceof SolrDocumentList) {
                    final List<Map<String, Object>> docMapList = new ArrayList<Map<String, Object>>(
                            ((SolrDocumentList) docList).size());
                    for (final SolrDocument solrDoc : (SolrDocumentList) docList) {
                        final Map<String, Object> docMap = new HashMap<String, Object>();
                        docMap.putAll(solrDoc);
                        docMapList.add(docMap);
                    }
                    moreLikeThisResponse.put(id, docMapList);
                }
            }
        }

        // docValues
        final Object docValuesObj = queryResponse.getResponse().get(DOC_VALUES);
        if (docValuesObj instanceof SimpleOrderedMap) {
            @SuppressWarnings("unchecked")
            final SimpleOrderedMap<List<Long>> docValuesMap = (SimpleOrderedMap<List<Long>>) docValuesObj;
            for (int i = 0; i < docValuesMap.size(); i++) {
                final String name = docValuesMap.getName(i);
                final List<Long> valueList = docValuesMap.getVal(i);
                for (int j = 0; j < valueList.size() && j < parent.size(); j++) {
                    parent.get(j).put(name, valueList.get(j));
                }
            }
        }
    }
    calculatePageInfo(start, pageSize, numFound);
}