Example usage for org.apache.solr.client.solrj.response QueryResponse getFacetDates

List of usage examples for org.apache.solr.client.solrj.response QueryResponse getFacetDates

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj.response QueryResponse getFacetDates.

Prototype

public List<FacetField> getFacetDates() 

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   ww w.  jav a  2 s .co 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:au.org.ala.biocache.dao.SearchDAOImpl.java

License:Open Source License

@Cacheable(cacheName = "legendCache")
public List<LegendItem> getLegend(SpatialSearchRequestParams searchParams, String facetField,
        String[] cutpoints) throws Exception {
    List<LegendItem> legend = new ArrayList<LegendItem>();

    queryFormatUtils.formatSearchQuery(searchParams);
    if (logger.isInfoEnabled()) {
        logger.info("search query: " + searchParams.getFormattedQuery());
    }// w w  w  . ja v  a 2 s  .c om
    SolrQuery solrQuery = new SolrQuery();
    solrQuery.setQueryType("standard");
    solrQuery.setQuery(searchParams.getFormattedQuery());
    solrQuery.setRows(0);
    solrQuery.setFacet(true);

    //is facet query?
    if (cutpoints == null) {
        //special case for the decade
        if (DECADE_FACET_NAME.equals(facetField))
            initDecadeBasedFacet(solrQuery, "occurrence_year");
        else
            solrQuery.addFacetField(facetField);
    } else {
        solrQuery.addFacetQuery("-" + facetField + ":[* TO *]");

        for (int i = 0; i < cutpoints.length; i += 2) {
            solrQuery.addFacetQuery(facetField + ":[" + cutpoints[i] + " TO " + cutpoints[i + 1] + "]");
        }
    }

    solrQuery.setFacetMinCount(1);
    solrQuery.setFacetLimit(-1);//MAX_DOWNLOAD_SIZE);  // unlimited = -1

    solrQuery.setFacetMissing(true);

    QueryResponse qr = runSolrQuery(solrQuery, searchParams.getFormattedFq(), 1, 0, "score", "asc");
    List<FacetField> facets = qr.getFacetFields();
    if (facets != null) {
        for (FacetField facet : facets) {
            List<FacetField.Count> facetEntries = facet.getValues();
            if (facet.getName().contains(facetField) && (facetEntries != null) && (facetEntries.size() > 0)) {
                int i = 0;
                for (i = 0; i < facetEntries.size(); i++) {
                    FacetField.Count fcount = facetEntries.get(i);
                    if (fcount.getCount() > 0) {
                        String fq = facetField + ":\"" + fcount.getName() + "\"";
                        if (fcount.getName() == null) {
                            fq = "-" + facetField + ":[* TO *]";
                        }
                        legend.add(new LegendItem(fcount.getName(), fcount.getCount(), fq));
                    }
                }
                break;
            }
        }
    }
    //check if we have query based facets
    Map<String, Integer> facetq = qr.getFacetQuery();
    if (facetq != null && facetq.size() > 0) {
        for (Entry<String, Integer> es : facetq.entrySet()) {
            legend.add(new LegendItem(es.getKey(), es.getValue(), es.getKey()));
        }
    }

    //check to see if we have a date range facet
    List<FacetField> facetDates = qr.getFacetDates();
    if (facetDates != null && !facetDates.isEmpty()) {
        FacetField ff = facetDates.get(0);
        String firstDate = null;
        for (FacetField.Count facetEntry : ff.getValues()) {
            String startDate = facetEntry.getName();
            if (firstDate == null) {
                firstDate = startDate;
            }
            String finishDate;
            if (DECADE_PRE_1850_LABEL.equals(startDate)) {
                startDate = "*";
                finishDate = firstDate;
            } else {
                int startYear = Integer.parseInt(startDate.substring(0, 4));
                finishDate = (startYear - 1) + "-12-31T23:59:59Z";
            }
            legend.add(new LegendItem(facetEntry.getName(), facetEntry.getCount(),
                    "occurrence_year:[" + startDate + " TO " + finishDate + "]"));
        }
    }
    return legend;
}

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

License:Open Source License

private void populateFacetField(QueryResponse aQueryResponse) {
    Logger appLogger = mAppMgr.getLogger(this, "populateFacetField");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    List<FacetField> facetFields = aQueryResponse.getFacetFields();
    List<FacetField> facetDateFields = aQueryResponse.getFacetDates();
    if ((facetFields != null) || (facetDateFields != null)) {
        mDocument.addRelationship(Solr.RESPONSE_FACET_FIELD, createFacetFieldBag());
        Relationship facetRelationship = mDocument.getFirstRelationship(Solr.RESPONSE_FACET_FIELD);
        if (facetRelationship != null) {
            DataBag facetBag = new DataBag(facetRelationship.getBag());
            facetBag.setAssignedFlagAll(false);
            DataTable facetTable = new DataTable(facetBag);
            if (facetFields != null) {
                for (FacetField facetField : facetFields)
                    populateFacet(facetTable, facetField);
            }/*www  .j  a va  2 s. c o m*/
            if (facetDateFields != null) {
                for (FacetField facetField : facetDateFields)
                    populateFacet(facetTable, facetField);
            }
            Document facetDocument = new Document(Solr.RESPONSE_FACET_FIELD, facetTable);
            facetRelationship.add(facetDocument);
        }
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:fr.paris.lutece.plugins.search.solr.business.SolrSearchEngine.java

License:Open Source License

/**
 * Return the result with facets. Does NOT support authentification yet.
 * @param strQuery the query//ww  w . ja  v a2  s.  co m
 * @param facetQueries The selected facets
 * @param sortName The facet name to sort by
 * @param sortOrder "asc" or "desc"
 * @param nLimit Maximal number of results.
 * @return the result with facets
 */
public SolrFacetedResult getFacetedSearchResults(String strQuery, String[] facetQueries, String sortName,
        String sortOrder, int nLimit, int nCurrentPageIndex, int nItemsPerPage, Boolean bSpellCheck) {
    SolrFacetedResult facetedResult = new SolrFacetedResult();

    SolrClient solrServer = SolrServerService.getInstance().getSolrServer();
    List<SolrSearchResult> results = new ArrayList<SolrSearchResult>();
    Hashtable<Field, List<String>> myValuesList = new Hashtable<Field, List<String>>();

    if (solrServer != null) {
        SolrQuery query = new SolrQuery(strQuery);
        query.setHighlight(true);
        query.setHighlightSimplePre(SOLR_HIGHLIGHT_PRE);
        query.setHighlightSimplePost(SOLR_HIGHLIGHT_POST);
        query.setHighlightSnippets(SOLR_HIGHLIGHT_SNIPPETS);
        query.setHighlightFragsize(SOLR_HIGHLIGHT_FRAGSIZE);
        query.setFacet(true);
        query.setFacetLimit(SOLR_FACET_LIMIT);
        //            query.setFacetMinCount( 1 );

        for (Field field : SolrFieldManager.getFacetList().values()) {
            //Add facet Field
            if (field.getEnableFacet()) {
                if (field.getName().equalsIgnoreCase("date")
                        || field.getName().toLowerCase().endsWith("_date")) {
                    query.setParam("facet.date", field.getName());
                    query.setParam("facet.date.start", SOLR_FACET_DATE_START);
                    query.setParam("facet.date.gap", SOLR_FACET_DATE_GAP);
                    query.setParam("facet.date.end", SOLR_FACET_DATE_END);
                    query.setParam("facet.date.mincount", "0");
                } else {
                    query.addFacetField(field.getSolrName());
                    query.setParam("f." + field.getSolrName() + ".facet.mincount",
                            String.valueOf(field.getFacetMincount()));
                }
                myValuesList.put(field, new ArrayList<String>());
            }
        }

        //Facet intersection
        List<String> treeParam = new ArrayList<String>();

        for (FacetIntersection intersect : SolrFieldManager.getIntersectionlist()) {
            treeParam.add(intersect.getField1().getSolrName() + "," + intersect.getField2().getSolrName());
        }

        //(String []) al.toArray (new String [0]);
        query.setParam("facet.tree", (String[]) treeParam.toArray(new String[0]));
        query.setParam("spellcheck", bSpellCheck);

        //sort order
        if ((sortName != null) && !"".equals(sortName)) {
            if (sortOrder.equals("asc")) {
                query.setSort(sortName, ORDER.asc);
            } else {
                query.setSort(sortName, ORDER.desc);
            }
        } else {
            for (Field field : SolrFieldManager.getSortList()) {
                if (field.getDefaultSort()) {
                    query.setSort(field.getName(), ORDER.desc);
                }
            }
        }

        //Treat HttpRequest
        //FacetQuery
        if (facetQueries != null) {
            for (String strFacetQuery : facetQueries) {
                //                    if ( strFacetQuery.contains( DATE_COLON ) )
                //                    {
                //                        query.addFilterQuery( strFacetQuery );
                //                    }
                //                    else
                //                    {
                String myValues[] = strFacetQuery.split(":", 2);
                if (myValues != null && myValues.length == 2) {
                    myValuesList = getFieldArrange(myValues, myValuesList);
                }
                //strFacetQueryWithColon = strFacetQuery.replaceFirst( SolrConstants.CONSTANT_COLON, COLON_QUOTE );
                //strFacetQueryWithColon += SolrConstants.CONSTANT_QUOTE;
                //                        query.addFilterQuery( strFacetQuery );
                //                    }
            }

            for (Field tmpFieldValue : myValuesList.keySet()) {
                List<String> strValues = myValuesList.get(tmpFieldValue);
                String strFacetString = "";
                if (strValues.size() > 0) {
                    strFacetString = extractQuery(strValues, tmpFieldValue.getOperator());
                    if (tmpFieldValue.getName().equalsIgnoreCase("date")
                            || tmpFieldValue.getName().toLowerCase().endsWith("_date")) {
                        strFacetString = strFacetString.replaceAll("\"", "");
                    }
                    query.addFilterQuery(tmpFieldValue.getName() + ":" + strFacetString);
                }
            }
        }

        try {

            // count query
            query.setRows(0);
            QueryResponse response = solrServer.query(query);

            int nResults = (int) response.getResults().getNumFound();
            facetedResult.setCount(nResults > nLimit ? nLimit : nResults);

            query.setStart((nCurrentPageIndex - 1) * nItemsPerPage);
            query.setRows(nItemsPerPage > nLimit ? nLimit : nItemsPerPage);

            query.setParam("defType", DEF_TYPE);
            String strWeightValue = generateQueryWeightValue();
            query.setParam("qf", strWeightValue);

            response = solrServer.query(query);

            //HighLight
            Map<String, Map<String, List<String>>> highlightsMap = response.getHighlighting();
            SolrHighlights highlights = null;

            if (highlightsMap != null) {
                highlights = new SolrHighlights(highlightsMap);
            }

            //resultList
            List<SolrItem> itemList = response.getBeans(SolrItem.class);
            results = SolrUtil.transformSolrItemsToSolrSearchResults(itemList, highlights);

            //set the spellcheckresult
            facetedResult.setSolrSpellCheckResponse(response.getSpellCheckResponse());

            //Date facet
            if ((response.getFacetDates() != null) && !response.getFacetDates().isEmpty()) {
                facetedResult.setFacetDateList(response.getFacetDates());
            }

            //FacetField
            facetedResult.setFacetFields(response.getFacetFields());

            //Facet intersection (facet tree)
            NamedList<Object> resp = (NamedList<Object>) response.getResponse().get("facet_counts");

            if (resp != null) {
                NamedList<NamedList<NamedList<Integer>>> trees = (NamedList<NamedList<NamedList<Integer>>>) resp
                        .get("trees");
                Map<String, ArrayList<FacetField>> treesResult = new HashMap<String, ArrayList<FacetField>>();

                if (trees != null) {
                    for (Entry<String, NamedList<NamedList<Integer>>> selectedFacet : trees) { //Selected Facet (ex : type,categorie )
                                                                                               //System.out.println(selectedFacet.getKey());

                        ArrayList<FacetField> facetFields = new ArrayList<FacetField>(
                                selectedFacet.getValue().size());

                        for (Entry<String, NamedList<Integer>> facetField : selectedFacet.getValue()) {
                            FacetField ff = new FacetField(facetField.getKey());

                            //System.out.println("\t" + facetField.getKey());
                            for (Entry<String, Integer> value : facetField.getValue()) { // Second Level
                                ff.add(value.getKey(), value.getValue());

                                //System.out.println("\t\t" + value.getKey() + " : " + value.getValue());
                            }

                            facetFields.add(ff);
                        }

                        treesResult.put(selectedFacet.getKey(), facetFields);
                    }
                }

                facetedResult.setFacetIntersection(treesResult);
            }
        } catch (SolrServerException e) {
            AppLogService.error(e.getMessage(), e);
        } catch (IOException e) {
            AppLogService.error(e.getMessage(), e);
        }
    } else {
        facetedResult.setFacetFields(new ArrayList<FacetField>());
    }

    facetedResult.setSolrSearchResults(results);

    return facetedResult;
}