Example usage for org.apache.solr.client.solrj.response GroupResponse getValues

List of usage examples for org.apache.solr.client.solrj.response GroupResponse getValues

Introduction

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

Prototype

public List<GroupCommand> getValues() 

Source Link

Document

Returns all grouping commands.

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  av  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.// w  ww . j  a  va2 s .  com
 * <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();
    }//ww w.  j  a v  a  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.nridge.ds.solr.SolrResponseBuilder.java

License:Open Source License

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

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    GroupResponse groupResponse = aQueryResponse.getGroupResponse();
    if (groupResponse != null) {
        mDocument.addRelationship(Solr.RESPONSE_GROUP, createGroupsBag());
        Relationship groupRelationship = mDocument.getFirstRelationship(Solr.RESPONSE_GROUP);
        if (groupRelationship != null) {
            DataBag groupingBag = groupRelationship.getBag();

            List<GroupCommand> groupCommandList = groupResponse.getValues();
            if (groupCommandList != null) {
                String groupName;

                DataField dfGroupName = groupingBag.getFieldByName("group_name");
                groupingBag.setValueByName("group_total", groupCommandList.size());

                for (GroupCommand groupCommand : groupCommandList) {
                    groupName = groupCommand.getName();
                    if (StringUtils.isNotEmpty(groupName))
                        dfGroupName.addValue(groupName);

                    groupingBag.setValueByName("group_matches", groupCommand.getMatches());

                    List<Group> groupList = groupCommand.getValues();
                    if (groupList != null) {
                        for (Group groupMember : groupList)
                            groupRelationship.add(createGroupCollectionDocument(groupMember));
                    }//w  ww .  ja  v a 2 s .c  o m
                }
            }
        }
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

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"));
                }// www  .  j ava 2 s.c  o  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  www .ja v a 2s .  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:org.broadleafcommerce.core.search.service.solr.SolrHelperServiceImpl.java

License:Apache License

@Override
public List<SolrDocument> getResponseDocuments(QueryResponse response) {
    List<SolrDocument> docs;

    if (response.getGroupResponse() == null) {
        docs = response.getResults();/*from   w  w w  .  j av  a  2 s  .c  o  m*/
    } else {
        docs = new ArrayList<SolrDocument>();
        GroupResponse gr = response.getGroupResponse();
        for (GroupCommand gc : gr.getValues()) {
            for (Group g : gc.getValues()) {
                for (SolrDocument d : g.getResult()) {
                    docs.add(d);
                }
            }
        }
    }

    return docs;
}

From source file:org.mousephenotype.cda.solr.service.PhenotypeCenterService.java

License:Apache License

public List<PhenotypeCenterServiceBean> getMutantStrainsForCenter(String center)
        throws SolrServerException, IOException {

    List<PhenotypeCenterServiceBean> strains = new ArrayList<>();
    SolrQuery query = new SolrQuery()
            .setQuery(ObservationDTO.PHENOTYPING_CENTER + ":\"" + center + "\" AND "
                    + ObservationDTO.BIOLOGICAL_SAMPLE_GROUP + ":experimental")
            .setFields(ObservationDTO.GENE_ACCESSION_ID, ObservationDTO.ALLELE_SYMBOL,
                    ObservationDTO.GENE_SYMBOL, ObservationDTO.ZYGOSITY)
            .setRows(1000000);/*from ww  w  . j  a  va 2s .  co m*/
    query.set("group", true);
    query.set("group.field", ObservationDTO.COLONY_ID);
    query.set("group.limit", 1);

    if (SolrUtils.getBaseURL(experimentCore).endsWith("experiment")) {
        query.addFilterQuery(ObservationDTO.DATASOURCE_NAME + ":" + "\"" + datasourceName + "\"");
    }
    QueryResponse response = experimentCore.query(query);
    GroupResponse groups = response.getGroupResponse();
    for (Group group : groups.getValues().get(0).getValues()) {
        PhenotypeCenterServiceBean strain = new PhenotypeCenterServiceBean();
        String colonyId = group.getGroupValue();
        if (colonyId != null && !colonyId.equalsIgnoreCase("null")) {
            strain.setColonyId(colonyId);
            SolrDocument doc = group.getResult().get(0);
            strain.setAllele((String) doc.get(ObservationDTO.ALLELE_SYMBOL));
            strain.setGeneSymbol((String) doc.get(ObservationDTO.GENE_SYMBOL));
            strain.setMgiAccession((String) doc.get(ObservationDTO.GENE_ACCESSION_ID));
            strain.setZygosity((String) doc.get(ObservationDTO.ZYGOSITY));
            strains.add(strain);
        }
    }
    logger.info("getStrainsForCenter -- " + SolrUtils.getBaseURL(experimentCore) + "/select?" + query);
    return strains;
}

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  ww  w  . jav a2s  . c o  m*/
                break;
            }
        }
    }
    return noResults;
}

From source file:org.opencommercesearch.AbstractSearchServerIntegrationTest.java

License:Apache License

@SearchTest(newInstance = true)
public void testDeleteByQuery(SearchServer server) throws SearchServerException {
    SolrQuery query = new SolrQuery("jacket");
    query.setRows(ROWS);/*from   w w w .  j  a  v  a2s .c  om*/
    SearchResponse res = server.search(query, site);
    QueryResponse queryResponse = res.getQueryResponse();
    GroupResponse groupResponse = queryResponse.getGroupResponse();

    assertNotEquals(new Integer(1), groupResponse.getValues().get(0).getNGroups());

    server.deleteByQuery("*:*");
    server.commit();
    res = server.search(query, site);
    queryResponse = res.getQueryResponse();
    groupResponse = queryResponse.getGroupResponse();
    assertEquals(new Integer(0), groupResponse.getValues().get(0).getNGroups());
}