Example usage for org.apache.solr.client.solrj.response GroupCommand getNGroups

List of usage examples for org.apache.solr.client.solrj.response GroupCommand getNGroups

Introduction

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

Prototype

public Integer getNGroups() 

Source Link

Document

Returns the total number of groups found for this command.

Usage

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

License:Open Source License

/**
 * Returns the count of distinct values for the facets.  Uses groups for group counts.
 * Supports foffset and flimit for paging. Supports fsort 'count' or 'index'.
 * <p/>//w w  w.j  a v  a2s.co m
 * TODO work out whether or not we should allow facet ranges to be downloaded....
 */
public List<FacetResultDTO> getFacetCounts(SpatialSearchRequestParams searchParams) throws Exception {
    Collection<FacetResultDTO> facetResults = new ArrayList<FacetResultDTO>();

    queryFormatUtils.formatSearchQuery(searchParams);
    String queryString = searchParams.getFormattedQuery();
    searchParams.setFacet(false);
    searchParams.setPageSize(0);

    //get facet group counts
    SolrQuery query = initSolrQuery(searchParams, false, null);
    query.setQuery(queryString);
    query.setFields(null);
    query.setRows(0);
    searchParams.setPageSize(0);

    //exclude multivalue fields
    Set<IndexFieldDTO> fields = getIndexedFields();
    List<String> multivalueFields = new ArrayList<String>();
    for (String facet : searchParams.getFacets()) {
        boolean added = false;
        for (IndexFieldDTO f : fields) {
            if (f.getName().equals(facet) && !f.isMultivalue()) {
                query.add("group.field", facet);
                added = true;
            }
        }
        if (!added) {
            multivalueFields.add(facet);
        }
    }

    if (multivalueFields.size() > 0) {
        facetResults.addAll(getMultivalueFacetCounts(query, searchParams, multivalueFields));
    }

    if (multivalueFields.size() < searchParams.getFacets().length) {
        //now use the supplied facets to add groups to the query

        // facet totals are slow, so only fetch when foffset == 0 and flimit != -1
        Map<String, Integer> ngroups = new HashMap<String, Integer>();
        GroupResponse groupResponse = null;
        if (searchParams.getFlimit() != -1 && searchParams.getFoffset() == 0) {
            query.add("group", "true");
            query.add("group.ngroups", "true");
            query.add("group.limit", "0");

            QueryResponse response = runSolrQuery(query, searchParams);
            groupResponse = response.getGroupResponse();
            for (GroupCommand gc : groupResponse.getValues()) {
                ngroups.put(gc.getName(), gc.getNGroups());
            }
        }

        //include paged facets when flimit > 0 or flimit == -1
        if (searchParams.getFlimit() != 0) {
            searchParams.setFacet(true);
            SolrQuery facetQuery = initSolrQuery(searchParams, false, null);
            facetQuery.setQuery(queryString);
            facetQuery.setFields(null);
            facetQuery.setSortField(searchParams.getSort(), ORDER.valueOf(searchParams.getDir()));
            QueryResponse qr = runSolrQuery(facetQuery, searchParams);
            SearchResultDTO searchResults = processSolrResponse(searchParams, qr, facetQuery,
                    OccurrenceIndex.class);
            facetResults = searchResults.getFacetResults();
            if (facetResults != null) {
                for (FacetResultDTO fr : facetResults) {
                    if (searchParams.getFlimit() == -1) {
                        fr.setCount(fr.getFieldResult().size());
                    } else {
                        Integer count = ngroups.get(fr.getFieldName());
                        if (count != null)
                            fr.setCount(count);
                    }
                }
            }
        } else if (groupResponse != null) {
            //only return group counts
            for (GroupCommand gc : groupResponse.getValues()) {
                facetResults.add(new FacetResultDTO(gc.getName(), null, gc.getNGroups()));
            }
        }
    }

    return new ArrayList<FacetResultDTO>(facetResults);
}

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

License:Open Source License

/**
 * Perform grouped facet query./*from  www .j  ava2  s.  co m*/
 * <p>
 * facets is the list of grouped facets required
 * flimit restricts the number of groups returned
 * pageSize restricts the number of docs in each group returned
 * fl is the list of fields in the returned docs
 */
public List<GroupFacetResultDTO> searchGroupedFacets(SpatialSearchRequestParams searchParams) throws Exception {
    queryFormatUtils.formatSearchQuery(searchParams);
    String queryString = searchParams.getFormattedQuery();
    searchParams.setFacet(false);

    //get facet group counts
    SolrQuery query = initSolrQuery(searchParams, false, null);
    query.setQuery(queryString);
    query.setFields(null);
    //now use the supplied facets to add groups to the query
    query.add("group", "true");
    query.add("group.ngroups", "true");
    query.add("group.limit", String.valueOf(searchParams.getPageSize()));
    query.setRows(searchParams.getFlimit());
    query.setFields(searchParams.getFl());
    for (String facet : searchParams.getFacets()) {
        query.add("group.field", facet);
    }
    QueryResponse response = runSolrQuery(query, searchParams);
    GroupResponse groupResponse = response.getGroupResponse();

    List<GroupFacetResultDTO> output = new ArrayList();
    for (GroupCommand gc : groupResponse.getValues()) {
        List<GroupFieldResultDTO> list = new ArrayList<GroupFieldResultDTO>();

        String facet = gc.getName();
        for (Group v : gc.getValues()) {
            List<OccurrenceIndex> docs = (new DocumentObjectBinder()).getBeans(OccurrenceIndex.class,
                    v.getResult());

            //build facet displayName and fq
            String value = v.getGroupValue();
            Long count = v.getResult() != null ? v.getResult().getNumFound() : 0L;
            if (value == null) {
                list.add(new GroupFieldResultDTO("", count, "-" + facet + ":*", docs));
            } else {
                list.add(new GroupFieldResultDTO(getFacetValueDisplayName(facet, value), count,
                        facet + ":\"" + value + "\"", docs));
            }
        }

        output.add(new GroupFacetResultDTO(gc.getName(), list, gc.getNGroups()));
    }

    return output;
}

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

License:Apache License

static <T> Map<Object, GroupResult<T>> convertGroupQueryResponseToGroupResultMap(Query query,
        Map<String, Object> objectNames, QueryResponse response, SolrTemplate solrTemplate, Class<T> clazz) {

    GroupResponse groupResponse = response.getGroupResponse();
    SolrDocumentList sdl = response.getResults();

    if (groupResponse == null) {
        return Collections.emptyMap();
    }/*from  ww w .  j a va 2  s .co m*/

    Map<Object, GroupResult<T>> result = new LinkedHashMap<Object, GroupResult<T>>();

    List<GroupCommand> values = groupResponse.getValues();
    for (GroupCommand groupCommand : values) {

        List<GroupEntry<T>> groupEntries = new ArrayList<GroupEntry<T>>();

        for (Group group : groupCommand.getValues()) {

            SolrDocumentList documentList = group.getResult();
            List<T> beans = solrTemplate.convertSolrDocumentListToBeans(documentList, clazz);
            Page<T> page = new PageImpl<T>(beans, query.getGroupOptions().getPageRequest(),
                    documentList.getNumFound());
            groupEntries.add(new SimpleGroupEntry<T>(group.getGroupValue(), page));
        }

        int matches = groupCommand.getMatches();
        Integer ngroups = groupCommand.getNGroups();
        String name = groupCommand.getName();

        PageImpl<GroupEntry<T>> page;
        if (ngroups != null) {
            page = new PageImpl<GroupEntry<T>>(groupEntries, query.getPageRequest(), ngroups.intValue());
        } else {
            page = new PageImpl<GroupEntry<T>>(groupEntries);
        }

        SimpleGroupResult<T> groupResult = new SimpleGroupResult<T>(matches, ngroups, name, page);
        result.put(name, groupResult);
        if (objectNames.containsKey(name)) {
            result.put(objectNames.get(name), groupResult);
        }
    }

    return result;
}

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

License:Apache License

@Test
public void testGroup() throws SolrServerException, IOException {
    SolrQuery solrQuery = new SolrQuery("*:*");

    solrQuery.set(GroupParams.GROUP, true);
    solrQuery.set(GroupParams.GROUP_TOTAL_COUNT, true);
    solrQuery.set(GroupParams.GROUP_LIMIT, 12);
    solrQuery.set(GroupParams.GROUP_FORMAT, "grouped");
    solrQuery.set(GroupParams.GROUP_FACET, true);
    solrQuery.set(GroupParams.GROUP_FIELD, "style");

    QueryResponse queryResponse = solrClient.query(solrQuery);
    GroupResponse groupResponse = queryResponse.getGroupResponse();
    if (null != groupResponse) {
        List<GroupCommand> groupCommandList = groupResponse.getValues();
        for (GroupCommand groupCommand : groupCommandList) {
            int matches = groupCommand.getMatches();
            String name = groupCommand.getName();
            Integer ngroups = groupCommand.getNGroups();

            List<Group> groupList = groupCommand.getValues();
            for (Group group : groupList) {
                SolrDocumentList solrDocumentList = group.getResult();
                ListIterator<SolrDocument> listIterator = solrDocumentList.listIterator();
                while (listIterator.hasNext()) {
                    SolrDocument solrDocument = listIterator.next();
                    System.out.println(solrDocument.get("code"));
                }//from   w w  w  . j av  a  2s  .  co m
            }
        }

    }
}

From source file:edu.unc.lib.dl.search.solr.service.SolrSearchService.java

License:Apache License

/**
 * Executes a SolrQuery based off of a search state and stores the results as BriefObjectMetadataBeans.
 * //from   w w  w.  j  a va 2 s  . c  o m
 * @param query
 *           the solr query to be executed
 * @param searchState
 *           the search state used to generate this SolrQuery
 * @param isRetrieveFacetsRequest
 *           indicates if facet results hould be returned
 * @param returnQuery
 *           indicates whether to return the solr query object as part of the response.
 * @return
 * @throws SolrServerException
 */
@SuppressWarnings("unchecked")
protected SearchResultResponse executeSearch(SolrQuery query, SearchState searchState,
        boolean isRetrieveFacetsRequest, boolean returnQuery) throws SolrServerException {
    QueryResponse queryResponse = server.query(query);

    GroupResponse groupResponse = queryResponse.getGroupResponse();
    SearchResultResponse response = new SearchResultResponse();
    if (groupResponse != null) {
        List<BriefObjectMetadata> groupResults = new ArrayList<BriefObjectMetadata>();
        for (GroupCommand groupCmd : groupResponse.getValues()) {
            // response.setResultCount(groupCmd.getMatches());
            response.setResultCount(groupCmd.getNGroups());
            for (Group group : groupCmd.getValues()) {
                GroupedMetadataBean grouped = new GroupedMetadataBean(group.getGroupValue(),
                        this.server.getBinder().getBeans(BriefObjectMetadataBean.class, group.getResult()),
                        group.getResult().getNumFound());
                groupResults.add(grouped);
            }
        }
        response.setResultList(groupResults);

    } else {
        List<?> results = queryResponse.getBeans(BriefObjectMetadataBean.class);
        response.setResultList((List<BriefObjectMetadata>) results);
        // Store the number of results
        response.setResultCount(queryResponse.getResults().getNumFound());
    }

    if (isRetrieveFacetsRequest) {
        // Store facet results
        response.setFacetFields(facetFieldFactory.createFacetFieldList(queryResponse.getFacetFields()));
        // Add empty entries for any empty facets, then sort the list
        if (response.getFacetFields() != null) {
            if (searchState.getFacetsToRetrieve() != null
                    && searchState.getFacetsToRetrieve().size() != response.getFacetFields().size()) {
                facetFieldFactory.addMissingFacetFieldObjects(response.getFacetFields(),
                        searchState.getFacetsToRetrieve());
            }
        }
    } else {
        response.setFacetFields(null);
    }

    // Set search state that generated this result
    response.setSearchState(searchState);

    // Add the query to the result if it was requested
    if (returnQuery) {
        response.setGeneratedQuery(query);
    }
    return response;
}

From source file:influent.server.search.SolrBaseSearchIterator.java

License:MIT License

protected void doRefresh(int startIdx, int pageSize) {
    try {//from w  ww  .j a va  2 s  .c  o m
        getLogger().info("fetching solr page : (@" + startIdx + " of size " + pageSize + ")");
        _query.setRows(pageSize).setStart(startIdx);
        _qResp = _server.query(_query, METHOD.POST);
        boolean isGroupedResponse = _qResp.getGroupResponse() != null;

        if (_totalResults == -1) {
            if (isGroupedResponse) {
                List<GroupCommand> groupCommands = _qResp.getGroupResponse().getValues();
                _totalResults = 0;
                for (GroupCommand cmd : groupCommands) {
                    _totalResults += cmd.getNGroups();
                }
            } else {
                _totalResults = (int) _qResp.getResults().getNumFound();
            }
        }
        _curResults.clear();

        if (isGroupedResponse) {
            List<GroupCommand> groupCommands = _qResp.getGroupResponse().getValues();
            for (GroupCommand cmd : groupCommands) {
                List<Group> groups = cmd.getValues();

                for (Group group : groups) {
                    SolrDocumentList groupResults = group.getResult();
                    FL_SearchResult es = new FL_SearchResult();
                    Object result = buildResultFromGroupedDocuments(groupResults);
                    es.setResult(result);
                    double score = ((Float) groupResults.get(0).getFieldValue("score")).doubleValue();
                    es.setMatchScore(score);
                    _curResults.add(es);
                }

            }
        } else {
            for (SolrDocument sd : _qResp.getResults()) {
                FL_SearchResult es = new FL_SearchResult();
                Object result = buildResultFromDocument(sd);
                es.setResult(result);
                double score = ((Float) sd.getFieldValue("score")).doubleValue();
                es.setMatchScore(score);
                _curResults.add(es);
            }
        }

        _nextLocalIdx = 0;
    } catch (SolrException e) {
        getLogger().error("Solr query error: " + e.getMessage());
        throw new AvroRuntimeException("Solr query error: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new AvroRuntimeException("Error paging search results " + e.getMessage(), e);
    }
}

From source file:org.opencommercesearch.AbstractSearchServer.java

License:Apache License

protected boolean isEmptySearch(GroupResponse groupResponse) {
    boolean noResults = true;
    if (groupResponse != null) {
        for (GroupCommand command : groupResponse.getValues()) {
            if (command.getNGroups() > 0) {
                noResults = false;//from   www  .ja v  a 2s  .co  m
                break;
            }
        }
    }
    return noResults;
}

From source file:org.opencommercesearch.EmbeddedServerIntegrationTest.java

License:Apache License

/**
 * For this test case there's really no need to use another data file. The only
 * reason I'm using is for the sake of showing how it works.
 *///from  w  w w  .  j  a  va 2  s.  c o  m
@SearchTest(newInstance = true, productData = "/product_catalog/bike-products.xml")
public void testUpdate(SearchServer server) throws SearchServerException {
    updateProduct(server);

    SolrQuery query = new SolrQuery("tallboy");

    query.setRows(ROWS);
    SearchResponse res = server.search(query, site);
    QueryResponse queryResponse = res.getQueryResponse();
    GroupResponse groupResponse = queryResponse.getGroupResponse();

    for (GroupCommand command : groupResponse.getValues()) {
        assertEquals(new Integer(1), command.getNGroups());

        for (Group group : command.getValues()) {
            assertEquals(false, group.getResult().get(0).getFieldValue("isToos"));
        }
    }
}

From source file:org.opencommercesearch.EmbeddedServerIntegrationTest.java

License:Apache License

@SearchTest
public void testSearch(SearchServer server) throws SearchServerException {
    SolrQuery query = new SolrQuery("face");
    query.setRows(ROWS);//from   w w  w. j av a2s. co m
    SearchResponse res = server.search(query, site);
    QueryResponse queryResponse = res.getQueryResponse();
    GroupResponse groupResponse = queryResponse.getGroupResponse();

    for (GroupCommand command : groupResponse.getValues()) {
        assertEquals(new Integer(1), command.getNGroups());

        for (Group group : command.getValues()) {
            assertEquals("PRD0001", group.getGroupValue());
        }
    }

}

From source file:org.opencommercesearch.EmbeddedServerIntegrationTest.java

License:Apache License

@SearchTest
public void testEmptySearch(SearchServer server) throws SearchServerException {

    SolrQuery query = new SolrQuery("bike");
    query.setRows(ROWS);//from   w ww  .ja va2 s  .c o  m
    SearchResponse res = server.search(query, site);
    QueryResponse queryResponse = res.getQueryResponse();
    GroupResponse groupResponse = queryResponse.getGroupResponse();

    for (GroupCommand command : groupResponse.getValues()) {
        assertEquals(new Integer(0), command.getNGroups());
    }
}