Example usage for org.apache.solr.client.solrj SolrQuery addFacetQuery

List of usage examples for org.apache.solr.client.solrj SolrQuery addFacetQuery

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj SolrQuery addFacetQuery.

Prototype

public SolrQuery addFacetQuery(String f) 

Source Link

Document

add a faceting query

Usage

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  .  j a  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.databasepreservation.visualization.utils.SolrUtils.java

private static void parseAndConfigureFacets(Facets facets, SolrQuery query) {
    if (facets != null) {
        query.setFacetSort(FacetParams.FACET_SORT_INDEX);
        if (!"".equals(facets.getQuery())) {
            query.addFacetQuery(facets.getQuery());
        }//from   w  w  w .  j  ava 2 s.c  o  m
        StringBuilder filterQuery = new StringBuilder();
        for (Map.Entry<String, FacetParameter> parameter : facets.getParameters().entrySet()) {
            FacetParameter facetParameter = parameter.getValue();

            if (facetParameter instanceof SimpleFacetParameter) {
                setQueryFacetParameter(query, (SimpleFacetParameter) facetParameter);
                appendValuesUsingOROperator(filterQuery, facetParameter.getName(),
                        ((SimpleFacetParameter) facetParameter).getValues());
            } else if (facetParameter instanceof RangeFacetParameter) {
                LOGGER.error("Unsupported facet parameter class: {}", facetParameter.getClass().getName());
            } else {
                LOGGER.error("Unsupported facet parameter class: {}", facetParameter.getClass().getName());
            }
        }
        if (filterQuery.length() > 0) {
            query.addFilterQuery(filterQuery.toString());
            LOGGER.trace("Query after defining facets: " + query.toString());
        }
    }
}

From source file:com.doculibre.constellio.services.FacetServicesImpl.java

License:Open Source License

public static SolrQuery toSolrQuery(SimpleSearch simpleSearch, int start, int row,
        boolean includeSingleValueFacets, boolean notIncludedOnly, List<String> customFieldFacets,
        List<String> customQueryFacets, ConstellioUser user) {
    String solrServerName = simpleSearch.getCollectionName();
    RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordCollection collection = collectionServices.get(solrServerName);
    SolrServices solrServices = ConstellioSpringUtils.getSolrServices();
    Boolean usesDisMax = solrServices.usesDisMax(collection);
    SolrQuery query;
    if (!collection.isOpenSearch()) {
        query = SearchServicesImpl.toSolrQuery(simpleSearch, usesDisMax, true, includeSingleValueFacets,
                notIncludedOnly);//from   w  w  w.  j a  v a 2 s  .com
    } else {
        query = SearchServicesImpl.toSolrQuery(simpleSearch, usesDisMax, false, true, false);
    }

    query.setParam(ConstellioSolrQueryParams.COLLECTION_NAME, simpleSearch.getCollectionName());
    query.setParam(ConstellioSolrQueryParams.LUCENE_QUERY,
            simpleSearch.getLuceneQuery(includeSingleValueFacets, true));
    query.setParam(ConstellioSolrQueryParams.SIMPLE_SEARCH, simpleSearch.toSimpleParams().toString());
    if (user != null) {
        query.setParam(ConstellioSolrQueryParams.USER_ID, "" + user.getId());
    }

    if (StringUtils.isEmpty(query.getQuery())) {
        query.setQuery(SimpleSearch.SEARCH_ALL);
        query.setRequestHandler("/elevate");
    }

    query.set("shards.qt", "/elevate");
    query.setRequestHandler("/elevate");

    query.setRows(row);
    query.setStart(start);
    query.setHighlight(true);
    query.setHighlightFragsize(100);
    query.setHighlightSnippets(2);

    query.setFacet(true);
    query.setFacetLimit(400);
    query.setFacetMinCount(1);

    if (collection.isOpenSearch()) {
        query.setParam("openSearchURL", collection.getOpenSearchURL());
        Locale locale = simpleSearch.getSingleSearchLocale();
        if (locale != null) {
            query.setParam("lang", locale.getLanguage());
        }
    } else {
        for (CollectionFacet collectionFacet : collection.getCollectionFacets()) {
            if (customFieldFacets == null && collectionFacet.isFieldFacet()) {
                IndexField indexField = collectionFacet.getFacetField();
                String indexFieldName = indexField.getName();
                if (!notIncludedOnly) {
                    query.addFacetField(indexFieldName);
                } else {
                    SearchedFacet searchedFacet = simpleSearch.getSearchedFacet(indexFieldName);
                    if (searchedFacet != null) {
                        if (!searchedFacet.getIncludedValues().isEmpty()) {
                            StringBuffer sbEx = new StringBuffer();
                            sbEx.append("{!ex=dt}");
                            //                                sbEx.append("{!ex=");
                            //                                boolean first = true;
                            //                                for (String includedValue : searchedFacet.getIncludedValues()) {
                            //                                    if (first) {
                            //                                        first = false;
                            //                                    } else {
                            //                                        sbEx.append(",");
                            //                                    }
                            //                                    sbEx.append(includedValue); 
                            //                                }
                            //                                sbEx.append("}");
                            //                                query.setParam("facet.field", sbEx.toString() + indexFieldName);
                            query.addFacetField(sbEx.toString() + indexFieldName);
                        } else {
                            query.addFacetField(indexFieldName);
                        }
                    }
                }
            } else if (customQueryFacets == null && collectionFacet.isQueryFacet()) {
                // Modification Rida, remplacement de collectionFacet.getLabels() par
                // collectionFacet.getLabelledValues()
                // for (I18NLabel valueLabels : collectionFacet.getLabels()) {
                for (I18NLabel valueLabels : collectionFacet.getLabelledValues()) {
                    String facetQuery = valueLabels.getKey();
                    query.addFacetQuery(facetQuery);
                }
            }
        }
        if (customFieldFacets != null) {
            for (String facetField : customFieldFacets) {
                if (!notIncludedOnly) {
                    query.addFacetField(facetField);
                } else {
                    StringBuffer sbEx = new StringBuffer();
                    sbEx.append("{!ex=dt}");
                    //                        sbEx.append("{!ex=");
                    //                        boolean first = true;
                    //                        for (String includedValue : searchedFacet.getIncludedValues()) {
                    //                            if (first) {
                    //                                first = false;
                    //                            } else {
                    //                                sbEx.append(",");
                    //                            }
                    //                            sbEx.append(includedValue); 
                    //                        }
                    //                        sbEx.append("}");
                    query.setParam("facet.field", sbEx.toString() + facetField);
                }
            }
        }

        if (customQueryFacets != null) {
            for (String facetQuery : customQueryFacets) {
                query.addFacetQuery(facetQuery);
            }
        }
    }

    return query;
}

From source file:com.frank.search.solr.core.DefaultQueryParser.java

License:Apache License

private void appendFacetingQueries(SolrQuery solrQuery, FacetQuery query) {
    FacetOptions facetOptions = query.getFacetOptions();
    for (SolrDataQuery fq : facetOptions.getFacetQueries()) {
        String facetQueryString = getQueryString(fq);
        if (StringUtils.isNotBlank(facetQueryString)) {
            solrQuery.addFacetQuery(facetQueryString);
        }/*from  w  w  w.j  ava  2 s. co m*/
    }
}

From source file:com.idealista.solrmeter.statistic.QueryLogStatisticTestCase.java

License:Apache License

private QueryException createQueryException() {
    QueryException queryException = new QueryException();
    SolrQuery query = new SolrQuery();
    query.setQuery("test");
    query.setFilterQueries("field=value");
    query.addFacetQuery("filterQuery=value");
    queryException.setQuery(query);//from   w  ww  . j av a 2 s.c  om
    return queryException;
}

From source file:com.liferay.portal.search.solr.facet.RangeFacetProcessor.java

License:Open Source License

@Override
public void processFacet(SolrQuery solrQuery, Facet facet) {
    FacetConfiguration facetConfiguration = facet.getFacetConfiguration();

    solrQuery.addFacetField(facetConfiguration.getFieldName());

    JSONObject dataJSONObject = facetConfiguration.getData();

    JSONArray rangesJSONArray = dataJSONObject.getJSONArray("ranges");

    if (rangesJSONArray == null) {
        return;/*from  w  w w. j a  v a2 s.  c o m*/
    }

    for (int i = 0; i < rangesJSONArray.length(); i++) {
        JSONObject rangeJSONObject = rangesJSONArray.getJSONObject(i);

        String range = rangeJSONObject.getString("range");

        String facetQuery = facetConfiguration.getFieldName() + StringPool.COLON + range;

        solrQuery.addFacetQuery(facetQuery);
    }
}

From source file:com.liferay.portal.search.solr.SolrIndexSearcherImpl.java

License:Open Source License

protected Hits doSearch(SearchContext searchContext, Query query) throws Exception {

    SolrQuery solrQuery = translateQuery(searchContext.getCompanyId(), query, searchContext.getSorts(),
            searchContext.getStart(), searchContext.getEnd());

    Map<String, Facet> facets = searchContext.getFacets();

    for (Facet facet : facets.values()) {
        if (facet.isStatic()) {
            continue;
        }//from   w ww. ja  va 2 s .  c  om

        FacetConfiguration facetConfiguration = facet.getFacetConfiguration();

        if (facet instanceof RangeFacet) {
            solrQuery.addFacetField(facetConfiguration.getFieldName());

            JSONObject dataJSONObject = facetConfiguration.getData();

            JSONArray rangesJSONArray = dataJSONObject.getJSONArray("ranges");

            if (rangesJSONArray == null) {
                continue;
            }

            for (int i = 0; i < rangesJSONArray.length(); i++) {
                JSONObject rangeJSONObject = rangesJSONArray.getJSONObject(i);

                String range = rangeJSONObject.getString("range");

                String facetQuery = facetConfiguration.getFieldName() + StringPool.COLON + range;

                solrQuery.addFacetQuery(facetQuery);
            }
        } else {
            solrQuery.addFacetField(facetConfiguration.getFieldName());
        }
    }

    solrQuery.setFacetLimit(-1);

    QueryResponse queryResponse = _solrServer.query(solrQuery);

    boolean allResults = false;

    if (solrQuery.getRows() == 0) {
        allResults = true;
    }

    List<FacetField> facetFields = queryResponse.getFacetFields();

    if (facetFields != null) {
        for (FacetField facetField : facetFields) {
            Facet facet = facets.get(facetField.getName());

            FacetCollector facetCollector = null;

            if (facet instanceof RangeFacet) {
                facetCollector = new SolrFacetQueryCollector(facetField.getName(),
                        queryResponse.getFacetQuery());
            } else {
                facetCollector = new SolrFacetFieldCollector(facetField.getName(), facetField);
            }

            facet.setFacetCollector(facetCollector);
        }
    }

    return subset(solrQuery, query, query.getQueryConfig(), queryResponse, allResults);
}

From source file:com.ssavr.solr.service.impl.IceCreamLocalServiceImpl.java

License:Open Source License

public List<IceCream> facetIceCreams(String facetValue) throws SystemException {
    if (_log.isDebugEnabled()) {
        _log.debug("facetIceCreams()");
    }/*from w w w .  j a  va  2s  . c om*/
    List<IceCream> iceCreams = new ArrayList<IceCream>();
    String activeServerURL = SolrUtil.getActiveSolrServer();

    try {
        CommonsHttpSolrServer server = new CommonsHttpSolrServer(activeServerURL);
        SolrQuery query = new SolrQuery();
        query.setQuery("*:*");
        query.setFacet(true);
        query.addFacetQuery("iceCreamName:" + facetValue);

        QueryResponse response = server.query(query);

        List<SolrResponse> searchResults = response.getBeans(SolrResponse.class);
        for (SolrResponse result : searchResults) {
            String iceCreamId = result.getEntryClassPK();
            IceCream iceCream = iceCreamPersistence.findByPrimaryKey(Long.parseLong(iceCreamId));
            iceCreams.add(iceCream);
        }

    } catch (MalformedURLException e) {
        if (_log.isDebugEnabled()) {
            _log.debug(e.getMessage());
        }
        throw new SystemException(e);
    } catch (SolrServerException e) {
        if (_log.isDebugEnabled()) {
            _log.debug(e.getMessage());
        }
        throw new SystemException(e);
    } catch (NoSuchIceCreamException e) {
        if (_log.isDebugEnabled()) {
            _log.debug(e.getMessage());
        }
        throw new SystemException(e);
    } catch (NumberFormatException e) {
        if (_log.isDebugEnabled()) {
            _log.debug(e.getMessage());
        }
        throw new SystemException(e);
    }

    return iceCreams;
}

From source file:com.yaotrue.learn.solr.SolrjTest.java

License:Apache License

@Test
public void testFacet() throws SolrServerException, IOException {
    SolrQuery solrQuery = new SolrQuery("*:*");
    solrQuery.setFacet(true);/*from  w  w w  .  j ava  2s  . c om*/
    solrQuery.addFacetQuery("sale_price:[0 TO 200]");
    solrQuery.addFacetQuery("sale_price:[201 TO 300]");
    solrQuery.addFacetQuery("sale_price:[300 TO 400]");
    solrQuery.setFacetSort("count");

    solrQuery.addFacetField("code");
    solrQuery.setFacetMinCount(0);
    solrQuery.setFacetLimit(-1);

    QueryResponse response = solrClient.query(solrQuery);
    if (response != null) {
        List<FacetField> facetFields = response.getFacetFields();
        for (FacetField facetField : facetFields) {
            List<Count> countList = null;
            if (facetField != null) {
                countList = facetField.getValues();
                if (countList != null) {
                    for (Count count : countList) {
                        System.out.println(count.getName() + count.getCount());
                    }
                }
            }
        }

        Map<String, Integer> map = response.getFacetQuery();
        for (String key : map.keySet()) {
            System.out.println(key + ":" + map.get(key));
        }
    }
}

From source file:io.vertigo.dynamo.plugins.search.solr.SolrStatement.java

License:Apache License

private static void appendFacetDefinition(final FacetedQueryDefinition queryDefinition,
        final SolrQuery solrQuery, final IndexFieldNameResolver indexFieldNameResolver) {
    Assertion.checkNotNull(solrQuery);/*w ww . j  ava  2 s  . c  om*/
    //---------------------------------------------------------------------
    //Activation des facettes
    final boolean hasFacet = !queryDefinition.getFacetDefinitions().isEmpty();
    solrQuery.setFacet(hasFacet);

    for (final FacetDefinition facetDefinition : queryDefinition.getFacetDefinitions()) {
        //Rcupration des noms des champs correspondant aux facettes.
        final DtField dtField = facetDefinition.getDtField();
        if (facetDefinition.isRangeFacet()) {
            //facette par range
            for (final FacetValue facetRange : facetDefinition.getFacetRanges()) {
                solrQuery.addFacetQuery(translateToSolr(facetRange.getListFilter(), indexFieldNameResolver));
            }
        } else {
            //facette par field
            solrQuery.addFacetField(indexFieldNameResolver.obtainIndexFieldName(dtField));
        }
    }
}