org.apache.solr.client.solrj.response.FacetField.Count Java Examples

The following examples show how to use org.apache.solr.client.solrj.response.FacetField.Count. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ItemSearchServiceLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenSearchingWithFacetFields_thenAllMatchingFacetsShouldAvialble() throws Exception {
    itemSearchService.index("hm0001", "Brand1 Washing Machine", "CategoryA", 100f);
    itemSearchService.index("hm0002", "Brand1 Refrigerator", "CategoryA", 300f);
    itemSearchService.index("hm0003", "Brand2 Ceiling Fan", "CategoryB", 200f);
    itemSearchService.index("hm0004", "Brand2 Dishwasher", "CategoryB", 250f);

    SolrQuery query = new SolrQuery();
    query.setQuery("*:*");
    query.addFacetField("category");

    QueryResponse response = solrClient.query(query);
    List<Count> facetResults = response.getFacetField("category").getValues();

    assertEquals(2, facetResults.size());

    for (Count count : facetResults) {
        if ("categorya".equalsIgnoreCase(count.getName())) {
            assertEquals(2, count.getCount());
        } else if ("categoryb".equalsIgnoreCase(count.getName())) {
            assertEquals(2, count.getCount());
        } else {
            fail("unexpected category");
        }
    }
}
 
Example #2
Source File: ServiceLogsManager.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends LogData> T createNewFieldByType(Class<T> clazz, Count count) {
  String temp = count.getName();
  LogData result;
  if (clazz.equals(SolrHostLogData.class)) {
    result = new SolrHostLogData();
    ((SolrHostLogData)result).setHost(temp);
  } else if (clazz.equals(SolrComponentTypeLogData.class)) {
    result = new SolrComponentTypeLogData();
    ((SolrComponentTypeLogData)result).setType(temp);
  } else {
    throw new UnsupportedOperationException();
  }
  
  return (T)result;
}
 
Example #3
Source File: SolrDocumentSearch.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
private Map<String, List<FacetEntry>> extractFacets(QueryResponse response, FacetStyle facetStyle) {
	Map<String, List<FacetEntry>> facets = new HashMap<>();
	
	for (String name : config.getFacetFields()) {
		FacetField fld = response.getFacetField(name);
		if (fld != null && !fld.getValues().isEmpty()) {
			List<FacetEntry> facetValues = new ArrayList<>();
			for (Count count : fld.getValues()) {
				facetValues.add(new FacetEntry(count.getName(), count.getCount()));
			}
			facets.put(name, facetValues);
		}
	}
	
	// And extract the facet tree, if there is one
	if (facetStyle != FacetStyle.NONE) {
		List<Object> facetTree = findFacetTree(response, EFO_URI_FIELD);
		if (facetTree != null && !facetTree.isEmpty()) {
			facets.put(EFO_URI_FIELD + "_hierarchy", extractFacetTreeFromNamedList(facetTree));
		}
	}
	
	return facets;
}
 
Example #4
Source File: ResponseDataGenerator.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public List<NameValueData> generateNameValueDataList(List<RangeFacet> rangeFacet) {
  List<NameValueData> nameValues = new ArrayList<>();
  if (rangeFacet == null) {
    return nameValues;
  }
  RangeFacet<?, ?> range = rangeFacet.get(0);

  if (range == null) {
    return nameValues;
  }
  List<RangeFacet.Count> listCount = range.getCounts();
  for (RangeFacet.Count cnt : listCount) {
    NameValueData nameValue = new NameValueData();
    nameValue.setName(String.valueOf(cnt.getValue()));
    nameValue.setValue(String.valueOf(cnt.getCount()));
    nameValues.add(nameValue);
  }
  return nameValues;
}
 
Example #5
Source File: ResponseDataGenerator.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
public List<Count> generateCount(QueryResponse response) {
  List<Count> counts = new ArrayList<>();
  List<FacetField> facetFields = null;
  FacetField facetField = null;
  if (response == null) {
    return counts;
  }

  facetFields = response.getFacetFields();
  if (facetFields == null) {
    return counts;
  }
  if (!facetFields.isEmpty()) {
    facetField = facetFields.get(0);
  }
  if (facetField != null) {
    counts = facetField.getValues();
  }
  return counts;
}
 
Example #6
Source File: ResponseDataGenerator.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
public Map<String, String> generateComponentMetadata(QueryResponse queryResponse,
                                                     String facetField, Map<String, String> componetnLabels) {
  Map<String, String> result = new HashMap<>();
  if (queryResponse == null) {
    return result;
  }
  FacetField facetFields = queryResponse.getFacetField(facetField);
  if (facetFields == null) {
    return result;
  }
  List<Count> counts = facetFields.getValues();
  if (counts == null) {
    return result;
  }
  for (Count count : counts) {
    if (count.getName() != null) {
      String label = componetnLabels.get(count.getName());
      String fallbackedLabel = labelFallbackHandler.fallbackIfRequired(count.getName(), label, true, false, true);
      result.put(count.getName(), fallbackedLabel);
    }
  }
  return result;
}
 
Example #7
Source File: ResultHelper.java    From dubbox with Apache License 2.0 5 votes vote down vote up
static Map<Field, Page<FacetFieldEntry>> convertFacetQueryResponseToFacetPageMap(FacetQuery query,
		QueryResponse response) {
	Assert.notNull(query, "Cannot convert response for 'null', query");

	if (!hasFacets(query, response)) {
		return Collections.emptyMap();
	}
	Map<Field, Page<FacetFieldEntry>> facetResult = new HashMap<Field, Page<FacetFieldEntry>>();

	if (CollectionUtils.isNotEmpty(response.getFacetFields())) {
		int initalPageSize = query.getFacetOptions().getPageable().getPageSize();
		for (FacetField facetField : response.getFacetFields()) {
			if (facetField != null && StringUtils.hasText(facetField.getName())) {
				Field field = new SimpleField(facetField.getName());
				if (CollectionUtils.isNotEmpty(facetField.getValues())) {
					List<FacetFieldEntry> pageEntries = new ArrayList<FacetFieldEntry>(initalPageSize);
					for (Count count : facetField.getValues()) {
						if (count != null) {
							pageEntries.add(new SimpleFacetFieldEntry(field, count.getName(), count.getCount()));
						}
					}
					facetResult.put(field, new SolrResultPage<FacetFieldEntry>(pageEntries,
							query.getFacetOptions().getPageable(), facetField.getValueCount(), null));
				} else {
					facetResult.put(field,
							new SolrResultPage<FacetFieldEntry>(Collections.<FacetFieldEntry> emptyList(),
									query.getFacetOptions().getPageable(), 0, null));
				}
			}
		}
	}
	return facetResult;
}
 
Example #8
Source File: SolrSearchDao.java    From metron with Apache License 2.0 5 votes vote down vote up
protected Map<String, Map<String, Long>> getFacetCounts(List<String> fields,
    QueryResponse solrResponse) {
  Map<String, Map<String, Long>> fieldCounts = new HashMap<>();
  for (String field : fields) {
    Map<String, Long> valueCounts = new HashMap<>();
    FacetField facetField = solrResponse.getFacetField(field);
    for (Count facetCount : facetField.getValues()) {
      valueCounts.put(facetCount.getName(), facetCount.getCount());
    }
    fieldCounts.put(field, valueCounts);
  }
  return fieldCounts;
}
 
Example #9
Source File: SolrProductSearch.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
private static List<Map<String, Object>> prepareAndRunSorlCategoryQuery(DispatchContext dctx, Map<String, Object> context, String catalogId,
        String categoryPath, String facetPrefix, int level) throws Exception {
    // TODO: Use this method in sideDeepCategories
    Map<String, Object> query = getAvailableCategories(dctx, context, catalogId, categoryPath, null, facetPrefix, false, 0, 0);
    if (ServiceUtil.isError(query)) {
        throw new Exception(ServiceUtil.getErrorMessage(query));
    }
    QueryResponse cat = (QueryResponse) query.get("rows");
    List<Map<String, Object>> result = UtilMisc.newList();
    List<FacetField> catList = (List<FacetField>) cat.getFacetFields();
    for (Iterator<FacetField> catIterator = catList.iterator(); catIterator.hasNext();) {
        FacetField field = (FacetField) catIterator.next();
        List<Count> catL = (List<Count>) field.getValues();
        if (catL != null) {
            for (Iterator<Count> catIter = catL.iterator(); catIter.hasNext();) {
                FacetField.Count facet = (FacetField.Count) catIter.next();
                if (facet.getCount() > 0) {
                    Map<String, Object> catMap = new HashMap<>();
                    List<String> iName = new LinkedList<>();
                    iName.addAll(Arrays.asList(facet.getName().split("/")));
                    catMap.put("catId", iName.get(iName.size() - 1)); 
                    iName.remove(0); // remove first
                    String path = facet.getName();
                    catMap.put("path", path);
                    if (level > 0) {
                        iName.remove(iName.size() - 1); // remove last
                        catMap.put("parentCategory", StringUtils.join(iName, "/"));
                    } else {
                        catMap.put("parentCategory", null);
                    }
                    catMap.put("count", Long.toString(facet.getCount()));
                    result.add(catMap);
                }
            }
        }
    }
    return result;
}
 
Example #10
Source File: ResultHelper.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * @param query
 * @param response
 * @return
 * @since 1.5
 */
static Map<Field, Page<FacetFieldEntry>> convertFacetQueryResponseToRangeFacetPageMap(FacetQuery query,
		QueryResponse response) {
	Assert.notNull(query, "Cannot convert response for 'null', query");

	if (!hasFacets(query, response) || isEmpty(response.getFacetRanges())) {
		return Collections.emptyMap();
	}
	Map<Field, Page<FacetFieldEntry>> facetResult = new HashMap<Field, Page<FacetFieldEntry>>();

	Pageable pageable = query.getFacetOptions().getPageable();
	int initalPageSize = pageable.getPageSize();
	for (RangeFacet<?, ?> rangeFacet : response.getFacetRanges()) {

		if (rangeFacet == null || !StringUtils.hasText(rangeFacet.getName())) {
			continue;
		}

		Field field = new SimpleField(rangeFacet.getName());

		List<FacetFieldEntry> entries;
		long total;
		if (isNotEmpty(rangeFacet.getCounts())) {
			entries = new ArrayList<FacetFieldEntry>(initalPageSize);
			for (RangeFacet.Count count : rangeFacet.getCounts()) {
				entries.add(new SimpleFacetFieldEntry(field, count.getValue(), count.getCount()));
			}
			total = rangeFacet.getCounts().size();
		} else {
			entries = Collections.<FacetFieldEntry> emptyList();
			total = 0;
		}

		facetResult.put(field, new SolrResultPage<FacetFieldEntry>(entries, pageable, total, null));

	}

	return facetResult;
}
 
Example #11
Source File: ServiceLogsManager.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
private <T extends LogData> List<T> getLogDataListByFieldType(Class<T> clazz, QueryResponse response, List<Count> fieldList) {
  List<T> groupList = getComponentBeans(clazz, response);
  for (Count cnt : fieldList) {
    T logData = createNewFieldByType(clazz, cnt);
    groupList.add(logData);
  }
  return groupList;
}
 
Example #12
Source File: ResponseDataGenerator.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
public CountDataListResponse generateCountResponseByField(QueryResponse response, String field) {
  CountDataListResponse collection = new CountDataListResponse();
  List<CountData> vCounts = new ArrayList<>();
  if (response == null) {
    return collection;
  }
  FacetField facetFields = response.getFacetField(field);
  if (facetFields == null) {
    return collection;
  }
  List<Count> fieldList = facetFields.getValues();

  if (fieldList == null) {
    return collection;
  }

  for (Count cnt : fieldList) {
    if (cnt != null) {
      CountData vCount = new CountData();
      vCount.setName(cnt.getName());
      vCount.setCount(cnt.getCount());
      vCounts.add(vCount);
    }
  }
  collection.setvCounts(vCounts);
  return collection;
}
 
Example #13
Source File: ResponseDataGenerator.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
public BarGraphDataListResponse generateBarGraphFromFieldFacet(QueryResponse response, String facetField) {
  BarGraphDataListResponse dataList = new BarGraphDataListResponse();
  Collection<BarGraphData> vaDatas = new ArrayList<>();
  dataList.setGraphData(vaDatas);
  if (response == null) {
    return dataList;
  }
  FacetField facetFieldObj = response.getFacetField(facetField);
  if (facetFieldObj == null) {
    return dataList;
  }

  List<Count> counts = facetFieldObj.getValues();
  if (counts == null) {
    return dataList;
  }
  for (Count cnt : counts) {
    List<NameValueData> valueList = new ArrayList<>();
    BarGraphData vBarGraphData = new BarGraphData();
    vaDatas.add(vBarGraphData);
    NameValueData vNameValue = new NameValueData();
    vNameValue.setName(cnt.getName());
    vBarGraphData.setName(cnt.getName().toUpperCase());
    vNameValue.setValue("" + cnt.getCount());
    valueList.add(vNameValue);
    vBarGraphData.setDataCount(valueList);
  }
  return dataList;
}
 
Example #14
Source File: AuditLogsManager.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
private List<LogData> getComponents(AuditComponentRequest request) {
  SimpleFacetQuery facetQuery = conversionService.convert(request, SimpleFacetQuery.class);
  List<LogData> docList = new ArrayList<>();
  QueryResponse queryResponse = auditSolrDao.process(facetQuery);
  List<Count> componentsCount = responseDataGenerator.generateCount(queryResponse);

  for (Count component : componentsCount) {
    SolrComponentTypeLogData logData = new SolrComponentTypeLogData();
    logData.setType(component.getName());
    docList.add(logData);
  }
  return docList;
}
 
Example #15
Source File: ServiceLogsManager.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
private <T extends LogData> GroupListResponse getFields(String field, String clusters, Class<T> clazz) {
  SolrQuery solrQuery = new SolrQuery();
  solrQuery.setQuery("*:*");
  SolrUtil.addListFilterToSolrQuery(solrQuery, CLUSTER, clusters);
  GroupListResponse collection = new GroupListResponse();
  SolrUtil.setFacetField(solrQuery, field);
  SolrUtil.setFacetSort(solrQuery, LogSearchConstants.FACET_INDEX);
  QueryResponse response = serviceLogsSolrDao.process(solrQuery);
  if (response == null) {
    return collection;
  }
  FacetField facetField = response.getFacetField(field);
  if (facetField == null) {
    return collection;
  }
  List<Count> fieldList = facetField.getValues();
  if (fieldList == null) {
    return collection;
  }
  SolrDocumentList docList = response.getResults();
  if (docList == null) {
    return collection;
  }
  List<LogData> groupList = new ArrayList<>(getLogDataListByFieldType(clazz, response, fieldList));

  collection.setGroupList(groupList);
  if (!docList.isEmpty()) {
    collection.setStartIndex((int) docList.getStart());
    collection.setTotalCount(docList.getNumFound());
  }
  return collection;
}
 
Example #16
Source File: SolrProductSearch.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
/**
 * Performs solr products search.
 */
public static Map<String, Object> solrProductsSearch(DispatchContext dctx, Map<String, Object> context) {
    Map<String, Object> result;
    LocalDispatcher dispatcher = dctx.getDispatcher();

    try {
        Map<String, Object> dispatchMap = dctx.makeValidContext("runSolrQuery", ModelService.IN_PARAM, context);

        if (UtilValidate.isNotEmpty(context.get("productCategoryId"))) {
            String productCategoryId = (String) context.get("productCategoryId");
            // causes erroneous results for similar-name categories
            //dispatchMap.put("query", "cat:*" + SolrUtil.escapeTermFull(productCategoryId) + "*");
            boolean includeSubCategories = !Boolean.FALSE.equals(context.get("includeSubCategories"));
            dispatchMap.put("query", SolrExprUtil.makeCategoryIdFieldQueryEscape("cat", productCategoryId, includeSubCategories));
        } else {
            return ServiceUtil.returnError("Missing productCategoryId"); // TODO: localize
        }
        Integer viewSize = (Integer) dispatchMap.get("viewSize");
        //Integer viewIndex = (Integer) dispatchMap.get("viewIndex");
        if (dispatchMap.get("facet") == null) dispatchMap.put("facet", false);
        if (dispatchMap.get("spellcheck") == null) dispatchMap.put("spellcheck", false); // 2017-09: default changed to false
        if (dispatchMap.get("highlight") == null) dispatchMap.put("highlight", false); // 2017-09: default changed to false

        List<String> queryFilters = getEnsureQueryFiltersModifiable(dispatchMap);
        SolrQueryUtil.addDefaultQueryFilters(queryFilters, context); // 2018-05-25

        Map<String, Object> searchResult = dispatcher.runSync("runSolrQuery", dispatchMap);
        if (!ServiceUtil.isSuccess(searchResult)) {
            return copySolrQueryExtraOutParams(searchResult, ServiceUtil.returnResultSysFields(searchResult));
        }
        QueryResponse queryResult = (QueryResponse) searchResult.get("queryResult");
        result = ServiceUtil.returnSuccess();

        Map<String, Integer> facetQuery = queryResult.getFacetQuery();
        Map<String, String> facetQueries = null;
        if (facetQuery != null) {
            facetQueries = new HashMap<>();
            for (String fq : facetQuery.keySet()) {
                if (facetQuery.get(fq) > 0) {
                    facetQueries.put(fq, fq.replaceAll("^.*\\u005B(.*)\\u005D", "$1") + " (" + facetQuery.get(fq).intValue() + ")");
                }
            }
        }

        List<FacetField> facets = queryResult.getFacetFields();
        Map<String, Map<String, Long>> facetFields = null;
        if (facets != null) {
            facetFields = new HashMap<>();
            for (FacetField facet : facets) {
                Map<String, Long> facetEntry = new HashMap<>();
                List<FacetField.Count> facetEntries = facet.getValues();
                if (UtilValidate.isNotEmpty(facetEntries)) {
                    for (FacetField.Count fcount : facetEntries) {
                        facetEntry.put(fcount.getName(), fcount.getCount());
                    }
                    facetFields.put(facet.getName(), facetEntry);
                }
            }
        }

        result.put("results", queryResult.getResults());
        result.put("facetFields", facetFields);
        result.put("facetQueries", facetQueries);
        result.put("listSize", queryResult.getResults().getNumFound());
        // 2016-04-01: Need to translate this
        //result.put("viewIndex", queryResult.getResults().getStart());
        result.put("start", queryResult.getResults().getStart());
        result.put("viewIndex", SolrQueryUtil.calcResultViewIndex(queryResult.getResults(), viewSize));
        result.put("viewSize", viewSize);
    } catch (Exception e) {
        Debug.logError(e, "Solr: productsSearch: " + e.getMessage(), module);
        result = ServiceUtil.returnError(e.toString());
    }
    return result;
}
 
Example #17
Source File: SolrProductSearch.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a map of the categories currently available under the root
 * element.
 */
public static Map<String, Object> solrAvailableCategories(DispatchContext dctx, Map<String, Object> context) {
    Map<String, Object> result;
    try {
        boolean displayProducts = Boolean.TRUE.equals(context.get("displayProducts"));
        int viewIndex = 0;
        int viewSize = 9;
        if (displayProducts) {
            viewIndex = (Integer) context.get("viewIndex");
            viewSize = (Integer) context.get("viewSize");
        }
        String catalogId = (String) context.get("catalogId");
        if (catalogId != null && catalogId.isEmpty()) catalogId = null; // TODO: REVIEW: is this necessary?

        List<String> currentTrail = UtilGenerics.checkList(context.get("currentTrail"));
        String productCategoryId = SolrCategoryUtil.getCategoryNameWithTrail((String) context.get("productCategoryId"),
                catalogId, dctx, currentTrail);
        String productId = (String) context.get("productId");
        if (Debug.verboseOn()) Debug.logVerbose("Solr: getAvailableCategories: productCategoryId: " + productCategoryId, module);
        Map<String, Object> query = getAvailableCategories(dctx, context, catalogId, productCategoryId, productId, null,
                displayProducts, viewIndex, viewSize);
        if (ServiceUtil.isError(query)) {
            throw new Exception(ServiceUtil.getErrorMessage(query));
        }

        QueryResponse cat = (QueryResponse) query.get("rows");
        result = ServiceUtil.returnSuccess();
        result.put("numFound", (long) 0);
        Map<String, Object> categories = new HashMap<>();
        List<FacetField> catList = (List<FacetField>) cat.getFacetFields();
        for (Iterator<FacetField> catIterator = catList.iterator(); catIterator.hasNext();) {
            FacetField field = (FacetField) catIterator.next();
            List<Count> catL = (List<Count>) field.getValues();
            if (catL != null) {
                // log.info("FacetFields = "+catL);
                for (Iterator<Count> catIter = catL.iterator(); catIter.hasNext();) {
                    FacetField.Count f = (FacetField.Count) catIter.next();
                    if (f.getCount() > 0) {
                        categories.put(f.getName(), Long.toString(f.getCount()));
                    }
                }
                result.put("categories", categories);
                result.put("numFound", cat.getResults().getNumFound());
                // log.info("The returned map is this:"+result);
            }
        }
    } catch (Exception e) {
        result = ServiceUtil.returnError(e.toString());
        result.put("numFound", (long) 0);
        return result;
    }
    return result;
}
 
Example #18
Source File: SolrProductSearch.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
/**
 * Return a map of the side deep categories.
 */
public static Map<String, Object> solrSideDeepCategory(DispatchContext dctx, Map<String, Object> context) {
    Map<String, Object> result;
    try {
        String catalogId = (String) context.get("catalogId");
        if (catalogId != null && catalogId.isEmpty()) catalogId = null; // TODO: REVIEW: is this necessary?
        List<String> currentTrail = UtilGenerics.checkList(context.get("currentTrail"));

        // 2016-03-22: FIXME?: I think we could call getCategoryNameWithTrail with showDepth=false,
        // instead of check in loop...
        String productCategoryId = SolrCategoryUtil.getCategoryNameWithTrail((String) context.get("productCategoryId"), catalogId, dctx, currentTrail);
        result = ServiceUtil.returnSuccess();
        Map<String, List<Map<String, Object>>> catLevel = new HashMap<>();
        if (Debug.verboseOn()) Debug.logVerbose("Solr: getSideDeepCategories: productCategoryId: " + productCategoryId, module);

        // Add toplevel categories
        String[] trailElements = productCategoryId.split("/");

        long numFound = 0;
        boolean isFirstElement = true;

        // iterate over actual results
        for (String element : trailElements) {
            if (Debug.verboseOn()) Debug.logVerbose("Solr: getSideDeepCategories: iterating element: " + element, module);
            List<Map<String, Object>> categories = new ArrayList<>();
            int level;
            // 2016-03-22: Don't make a query for the first element, which is the count,
            // but for compatibility, still make a map entry for it
            // NOTE: I think this could be skipped entirely because level 0 is replaced/taken by the
            // first category, but leaving in to play it safe
            if (isFirstElement) {
                level = 0;
                isFirstElement = false;
            } else {
                String categoryPath = SolrCategoryUtil.getCategoryNameWithTrail(element, catalogId, dctx, currentTrail);
                String[] categoryPathArray = categoryPath.split("/");
                level = Integer.parseInt(categoryPathArray[0]);
                String facetPrefix = SolrCategoryUtil.getFacetFilterForCategory(categoryPath, dctx);
                // 2016-03-22: IMPORTANT: the facetPrefix MUST end with / otherwise it will return unrelated categories!
                // solr facetPrefix is not aware of our path delimiters
                if (!facetPrefix.endsWith("/")) {
                    facetPrefix += "/";
                }
                // Debug.logInfo("categoryPath: "+categoryPath + "
                // facetPrefix: "+facetPrefix,module);
                Map<String, Object> query = getAvailableCategories(dctx, context, catalogId, categoryPath, null, facetPrefix, false, 0, 0);
                if (ServiceUtil.isError(query)) {
                    throw new Exception(ServiceUtil.getErrorMessage(query));
                }

                QueryResponse cat = (QueryResponse) query.get("rows");
                Long subNumFound = (Long) query.get("numFound");
                if (subNumFound != null) {
                    numFound += subNumFound;
                }
                List<FacetField> catList = (List<FacetField>) cat.getFacetFields();
                for (Iterator<FacetField> catIterator = catList.iterator(); catIterator.hasNext();) {
                    FacetField field = (FacetField) catIterator.next();
                    List<Count> catL = (List<Count>) field.getValues();
                    if (catL != null) {
                        for (Iterator<Count> catIter = catL.iterator(); catIter.hasNext();) {
                            FacetField.Count facet = (FacetField.Count) catIter.next();
                            if (facet.getCount() > 0) {
                                Map<String, Object> catMap = new HashMap<>();
                                List<String> iName = new LinkedList<>();
                                iName.addAll(Arrays.asList(facet.getName().split("/")));
                                // Debug.logInfo("topLevel "+topLevel,"");
                                // int l = Integer.parseInt((String)
                                // iName.getFirst());
                                catMap.put("catId", iName.get(iName.size() - 1)); // get last
                                iName.remove(0); // remove first
                                String path = facet.getName();
                                catMap.put("path", path);
                                if (level > 0) {
                                    iName.remove(iName.size() - 1); // remove last
                                    catMap.put("parentCategory", StringUtils.join(iName, "/"));
                                } else {
                                    catMap.put("parentCategory", null);
                                }
                                catMap.put("count", Long.toString(facet.getCount()));
                                categories.add(catMap);
                            }
                        }
                    }
                }
            }
            catLevel.put("menu-" + level, categories);
        }
        result.put("categories", catLevel);
        result.put("numFound", numFound);

    } catch (Exception e) {
        result = ServiceUtil.returnError(e.toString());
        result.put("numFound", (long) 0);
        return result;
    }
    return result;
}
 
Example #19
Source File: SearchITCase.java    From apache-solr-essentials with Apache License 2.0 4 votes vote down vote up
/**
 * Demonstrates how to ask for faceting and iterate over response facets.
 * 
 * @throws Exception hopefully never, otherwise the test fails.
 */
@Test
public void facets() throws Exception {
	// 1. Prepare the Query object
	// The query string can be directly injected in the constructor
	final SolrQuery query = new SolrQuery("*:*");
	query.setRequestHandler("/h1");
	
	// These settings will override the "defaults" section
	// Note that this handler sets facet to true, so the following line is
	// not actually needed
	query.setFacet(true);
	query.addFacetField("genre", "released");
	
	// We don't want highlighting here
	// Since the HL component is disabled by default, also this line is not needed.
	query.setHighlight(false);
	
	// We are only interested in facets, so skip don't include any 
	// document in the response.
	query.setRows(0);
	
	// 2. Send the query request and get the corresponding response.
	final QueryResponse response = SEARCHER.query(query);
	
	// 3. Get the result object, containing documents and metadata.
	final SolrDocumentList documents = response.getResults();
	
	// If not explicitly requested (or set in the handler) the start is set to 0
	assertEquals(0, documents.getStart());
	
	// Total number of documents found must be equals to all documents we previously indexed
	assertEquals(sampleData().size(), documents.getNumFound());
	
	// Page size must be 0, as requested
	assertEquals(0, documents.size());
	
	final FacetField genre = response.getFacetField("genre");
	assertNotNull(genre);
	 
	// This is something that should never appear within a TestCase :) 
	// however is useful to demonstrate how to iterate over facet values
	for (final Count count : genre.getValues()) {
		// e.g. Jazz : 19
		// e.g. Fusion: 11
		System.out.println(count.getName() + " : " + count.getCount());
	}
}