Java Code Examples for org.apache.solr.client.solrj.SolrQuery#setFacet()

The following examples show how to use org.apache.solr.client.solrj.SolrQuery#setFacet() . 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: AbstractDateRangeFacetQueryConverter.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Override
public SolrQuery convert(SOURCE request) {
  SolrQuery solrQuery = new SolrQuery();
  String unit = StringUtils.defaultIfEmpty(request.getUnit(), "+1HOUR");
  solrQuery.setQuery("*:*");
  solrQuery.setFacet(true);
  solrQuery.addFacetPivotField("{!range=r1}" + getTypeFieldName());
  solrQuery.setFacetMinCount(1);
  solrQuery.setFacetLimit(-1);
  solrQuery.setFacetSort(LogSearchConstants.FACET_INDEX);
  solrQuery.add("facet.range", "{!tag=r1}" + getDateFieldName());
  solrQuery.add(String.format(Locale.ROOT, "f.%s.%s", getDateFieldName(), "facet.range.start"), request.getFrom());
  solrQuery.add(String.format(Locale.ROOT, "f.%s.%s", getDateFieldName(), "facet.range.end"), request.getTo());
  solrQuery.add(String.format(Locale.ROOT, "f.%s.%s", getDateFieldName(), "facet.range.gap"), unit);
  solrQuery.remove("sort");
  solrQuery.setRows(0);
  solrQuery.setStart(0);
  return solrQuery;
}
 
Example 2
Source File: DefaultQueryParser.java    From dubbox with Apache License 2.0 6 votes vote down vote up
private boolean enableFaceting(SolrQuery solrQuery, FacetQuery query) {
	FacetOptions facetOptions = query.getFacetOptions();
	if (facetOptions == null || !facetOptions.hasFacets()) {
		return false;
	}
	solrQuery.setFacet(true);
	solrQuery.setFacetMinCount(facetOptions.getFacetMinCount());
	solrQuery.setFacetLimit(facetOptions.getPageable().getPageSize());
	if (facetOptions.getPageable().getPageNumber() > 0) {
		int offset = Math.max(0, facetOptions.getPageable().getOffset());
		solrQuery.set(FacetParams.FACET_OFFSET, offset);
	}
	if (FacetOptions.FacetSort.INDEX.equals(facetOptions.getFacetSort())) {
		solrQuery.setFacetSort(FacetParams.FACET_SORT_INDEX);
	}
	return true;
}
 
Example 3
Source File: SolrUtil.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
public static void setFacetPivot(SolrQuery solrQuery, int mincount, String... hirarchy) {
  solrQuery.setFacet(true);
  setRowCount(solrQuery, 0);
  solrQuery.set(LogSearchConstants.FACET_PIVOT, hirarchy);
  solrQuery.set(LogSearchConstants.FACET_PIVOT_MINCOUNT, mincount);
  setFacetLimit(solrQuery, -1);
}
 
Example 4
Source File: SolrDataSet.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void initSolrConfiguration(JSONObject jsonConf, boolean resolveParams) {
	try {
		solrConfiguration = new SolrConfiguration();
		String address = getProp(SolrDataSetConstants.SOLR_BASE_ADDRESS, jsonConf, false, resolveParams);
		solrConfiguration.setUrl(address);
		String collection = getProp(SolrDataSetConstants.SOLR_COLLECTION, jsonConf, false, resolveParams);
		solrConfiguration.setCollection(collection);
		SolrQuery solrQuery = new SolrQuery();
		String query = getProp(SolrDataSetConstants.SOLR_QUERY, jsonConf, true, resolveParams);
		if (query == null || query.isEmpty()) {
			query = SOLR_DEFAULT_QUERY;
		}
		solrQuery.setQuery(query);
		String fieldList = getProp(SolrDataSetConstants.SOLR_FIELD_LIST, jsonConf, true, resolveParams);
		if (fieldList != null && !fieldList.trim().isEmpty()) {
			solrQuery.setFields(fieldList.split(","));
		}
		String solrFields = getProp(SolrDataSetConstants.SOLR_FIELDS, jsonConf, true, resolveParams);
		if (solrFields != null && !solrFields.trim().isEmpty()) {
			solrConfiguration.setSolrFields(solrFields);
		}

		List<Couple<String, String>> filterQueries = getListProp(SolrDataSetConstants.SOLR_FILTER_QUERY, jsonConf, true);
		if (filterQueries != null && !filterQueries.isEmpty()) {
			String[] array = new String[filterQueries.size()];
			for (int i = 0; i < array.length; i++) {
				array[i] = filterQueries.get(i).getFirst() + ":" + filterQueries.get(i).getSecond();
			}

			solrQuery.setFilterQueries(array);
		}
		solrQuery.setFacet(isFacet());
		solrConfiguration.setSolrQuery(solrQuery);
	} catch (JSONException e) {
		throw new ConfigurationException("Problems in configuration of solr query", e);
	}
}
 
Example 5
Source File: SolrDataSet.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void initSolrConfiguration(JSONObject jsonConf, boolean resolveParams, UserProfile userProfile) {
	try {
		solrConfiguration = new SolrConfiguration();
		String address = getProp(SolrDataSetConstants.SOLR_BASE_ADDRESS, jsonConf, false, resolveParams);
		solrConfiguration.setUrl(address);
		String collection = getProp(SolrDataSetConstants.SOLR_COLLECTION, jsonConf, false, resolveParams);
		solrConfiguration.setCollection(collection);
		SolrQuery solrQuery = new SolrQuery();
		String query = getProp(SolrDataSetConstants.SOLR_QUERY, jsonConf, true, resolveParams);
		if (query == null || query.isEmpty()) {
			query = SOLR_DEFAULT_QUERY;
		}
		solrQuery.setQuery(query);
		String fieldList = getProp(SolrDataSetConstants.SOLR_FIELD_LIST, jsonConf, true, resolveParams);
		if (fieldList != null && !fieldList.trim().isEmpty()) {
			solrQuery.setFields(fieldList.split(","));
		}
		String solrFields = getProp(SolrDataSetConstants.SOLR_FIELDS, jsonConf, true, resolveParams);
		if (solrFields != null && !solrFields.trim().isEmpty()) {
			solrConfiguration.setSolrFields(solrFields);
		}

		List<Couple<String, String>> filterQueries = getListProp(SolrDataSetConstants.SOLR_FILTER_QUERY, jsonConf, true, userProfile);
		if (filterQueries != null && !filterQueries.isEmpty()) {
			String[] array = new String[filterQueries.size()];
			for (int i = 0; i < array.length; i++) {
				array[i] = filterQueries.get(i).getFirst() + ":" + filterQueries.get(i).getSecond();
			}

			solrQuery.setFilterQueries(array);
		}
		solrQuery.setFacet(isFacet());
		solrConfiguration.setSolrQuery(solrQuery);
	} catch (JSONException e) {
		throw new ConfigurationException("Problems in configuration of solr query", e);
	}
}
 
Example 6
Source File: SearchITCase.java    From apache-solr-essentials with Apache License 2.0 5 votes vote down vote up
/**
 * Selects all documents using an handler configured with SolrQueryParser
 * 
 * @throws Exception hopefully never, otherwise the test fails.
 */
@Test
public void selectAll() 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
	query.setFacet(false);
	query.setHighlight(false);
	query.setSort("released", ORDER.desc);
	
	// We are asking 5 documents per page
	query.setRows(5);
	
	// 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 5, as requested
	assertEquals(5, documents.size());
}
 
Example 7
Source File: SearchITCase.java    From apache-solr-essentials with Apache License 2.0 5 votes vote down vote up
/**
 * Illustrates how to execute a query with a response callback.
 * 
 * @throws Exception hopefully never, otherwise the test fails.
 */
@Test
public void withCallback() throws Exception {
	final int expectedWindowSize = 2;
	
	// 1. Prepare the Query object
	// The query string can be directly injected in the constructor. 
	// Note that the /h2 request handler uses a dismax query parser and 
	// therefore the query string is composed by just search term (no fields).
	final SolrQuery query = new SolrQuery("rock jazz");
	query.setRequestHandler("/h2");
	query.setFacet(false);
	query.setRows(expectedWindowSize);
	
	// 2. creates a callback handler
	final SampleStreamingResponseCallback callbackHandler = new SampleStreamingResponseCallback(4);
	
	// 3. Note that in this case we are not invoking "query" but "queryAndStreamResponse"
	// That requires the callback handler previously defined. 
	// That method still returns a QueryResponse but, as its javadoc says, 
	// it is not supposed to be used because streamed documents are removed from there.
	@SuppressWarnings("unused")
	final QueryResponse dontUseMe = SEARCHER.queryAndStreamResponse(query, callbackHandler);
	
	// 4. Assert window result
	assertEquals(expectedWindowSize, callbackHandler.getCurrentWindowSize());
}
 
Example 8
Source File: SolrUtil.java    From ambari-logsearch with Apache License 2.0 4 votes vote down vote up
public static void setFacetField(SolrQuery solrQuery, String facetField) {
  solrQuery.setFacet(true);
  setRowCount(solrQuery, 0);
  solrQuery.set(LogSearchConstants.FACET_FIELD, facetField);
  setFacetLimit(solrQuery, -1);
}
 
Example 9
Source File: SolrUtil.java    From ambari-logsearch with Apache License 2.0 4 votes vote down vote up
public static void setFacetSort(SolrQuery solrQuery, String sortType) {
  solrQuery.setFacet(true);
  solrQuery.setFacetSort(sortType);
}
 
Example 10
Source File: SolrProductSearch.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
/**
 * NOTE: This method is package-private for backward compat only and should not be made public; its interface is subject to change.
 * Client code should call the solrAvailableCategories or solrSideDeepCategory service instead.
 */
static Map<String, Object> getAvailableCategories(DispatchContext dctx, Map<String, Object> context,
        String catalogId, String categoryId, String productId, String facetPrefix, boolean displayProducts, int viewIndex, int viewSize) {
    Map<String, Object> result;

    try {
        HttpSolrClient client = SolrUtil.getQueryHttpSolrClient((String) context.get("core"));
        SolrQuery solrQuery = new SolrQuery();

        String query;
        if (categoryId != null) {
            query = "+cat:"+ SolrExprUtil.escapeTermFull(categoryId);
        } else if (productId != null) {
            query = "+productId:" + SolrExprUtil.escapeTermFull(productId);
        } else {
            query = "*:*";
        }
        solrQuery.setQuery(query);

        if (catalogId != null) {
            solrQuery.addFilterQuery("+catalog:" + SolrExprUtil.escapeTermFull(catalogId));
        }

        SolrQueryUtil.addDefaultQueryFilters(solrQuery, context);
        SolrQueryUtil.addFilterQueries(solrQuery, UtilGenerics.<String>checkList(context.get("queryFilters")));

        if (displayProducts) {
            if (viewSize > -1) {
                solrQuery.setRows(viewSize);
            } else
                solrQuery.setRows(50000);
            if (viewIndex > -1) {
                // 2016-04-01: This must be calculated
                //solrQuery.setStart(viewIndex);
                if (viewSize > 0) {
                    solrQuery.setStart(viewSize * viewIndex);
                }
            }
        } else {
            solrQuery.setFields("cat");
            solrQuery.setRows(0);
        }

        if(UtilValidate.isNotEmpty(facetPrefix)){
            solrQuery.setFacetPrefix(facetPrefix);
        }

        solrQuery.setFacetMinCount(0);
        solrQuery.setFacet(true);
        solrQuery.addFacetField("cat");
        solrQuery.setFacetLimit(-1);
        if (Debug.verboseOn()) Debug.logVerbose("solr: solrQuery: " + solrQuery, module);
        QueryResponse returnMap = client.query(solrQuery, METHOD.POST);
        result = ServiceUtil.returnSuccess();
        result.put("rows", returnMap);
        result.put("numFound", returnMap.getResults().getNumFound());
    } catch (Exception e) {
        Debug.logError(e.getMessage(), module);
        return ServiceUtil.returnError(e.getMessage());
    }
    return result;
}
 
Example 11
Source File: TestTolerantSearch.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public void testGetFieldsPhaseError() throws SolrServerException, IOException {
  BadResponseWriter.failOnGetFields = true;
  BadResponseWriter.failOnGetTopIds = false;
  SolrQuery query = new SolrQuery();
  query.setQuery("subject:batman OR subject:superman");
  query.addField("id");
  query.addField("subject");
  query.set("distrib", "true");
  query.set("shards", shard1 + "," + shard2);
  query.set(ShardParams.SHARDS_INFO, "true");
  query.set("debug", "true");
  query.set("stats", "true");
  query.set("stats.field", "id");
  query.set("mlt", "true");
  query.set("mlt.fl", "title");
  query.set("mlt.count", "1");
  query.set("mlt.mintf", "0");
  query.set("mlt.mindf", "0");
  query.setHighlight(true);
  query.addFacetField("id");
  query.setFacet(true);
  
  ignoreException("Dummy exception in BadResponseWriter");

  expectThrows(SolrException.class, () -> collection1.query(query));

  query.set(ShardParams.SHARDS_TOLERANT, "true");
  QueryResponse response = collection1.query(query);
  assertTrue(response.getResponseHeader().getBooleanArg(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY));
  NamedList<Object> shardsInfo = ((NamedList<Object>)response.getResponse().get(ShardParams.SHARDS_INFO));
  boolean foundError = false;
  for (int i = 0; i < shardsInfo.size(); i++) {
    if (shardsInfo.getName(i).contains("collection2")) {
      assertNotNull(((NamedList<Object>)shardsInfo.getVal(i)).get("error"));
      foundError = true;
      break;
    }
  }
  assertTrue(foundError);
  assertEquals("1", response.getResults().get(0).getFieldValue("id"));
  assertEquals("batman", response.getResults().get(0).getFirstValue("subject"));
  unIgnoreException("Dummy exception in BadResponseWriter");
}
 
Example 12
Source File: TestTolerantSearch.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public void testGetTopIdsPhaseError() throws SolrServerException, IOException {
  BadResponseWriter.failOnGetTopIds = true;
  BadResponseWriter.failOnGetFields = false;
  SolrQuery query = new SolrQuery();
  query.setQuery("subject:batman OR subject:superman");
  query.addField("id");
  query.addField("subject");
  query.set("distrib", "true");
  query.set("shards", shard1 + "," + shard2);
  query.set(ShardParams.SHARDS_INFO, "true");
  query.set("debug", "true");
  query.set("stats", "true");
  query.set("stats.field", "id");
  query.set("mlt", "true");
  query.set("mlt.fl", "title");
  query.set("mlt.count", "1");
  query.set("mlt.mintf", "0");
  query.set("mlt.mindf", "0");
  query.setHighlight(true);
  query.addFacetField("id");
  query.setFacet(true);
  
  ignoreException("Dummy exception in BadResponseWriter");

  expectThrows(Exception.class, () -> collection1.query(query));

  query.set(ShardParams.SHARDS_TOLERANT, "true");
  QueryResponse response = collection1.query(query);
  assertTrue(response.getResponseHeader().getBooleanArg(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY));
  NamedList<Object> shardsInfo = ((NamedList<Object>)response.getResponse().get(ShardParams.SHARDS_INFO));
  boolean foundError = false;
  for (int i = 0; i < shardsInfo.size(); i++) {
    if (shardsInfo.getName(i).contains("collection2")) {
      assertNotNull(((NamedList<Object>)shardsInfo.getVal(i)).get("error"));
      foundError = true;
      break;
    }
  }
  assertTrue(foundError);
  assertFalse(""+response, response.getResults().isEmpty());
  assertEquals("1", response.getResults().get(0).getFieldValue("id"));
  assertEquals("batman", response.getResults().get(0).getFirstValue("subject"));
  unIgnoreException("Dummy exception in BadResponseWriter");
}
 
Example 13
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());
	}
}
 
Example 14
Source File: SolrDocumentSearch.java    From BioSolr with Apache License 2.0 4 votes vote down vote up
@Override
public ResultsList<Document> searchDocuments(String term, int start, int rows, List<String> additionalFields,
		List<String> filters, FacetStyle facetStyle) throws SearchEngineException {
	ResultsList<Document> results = null;

	try {
		SolrQuery query = new SolrQuery(term);
		query.setStart(start);
		query.setRows(rows);
		query.setRequestHandler(config.getDocumentRequestHandler());
		List<String> queryFields = new ArrayList<>(DEFAULT_SEARCH_FIELDS);
		if (additionalFields != null) {
			queryFields.addAll(additionalFields);
		}
		if (filters != null) {
			query.addFilterQuery(filters.toArray(new String[0]));
		}
		query.setParam(DisMaxParams.QF, queryFields.toArray(new String[queryFields.size()]));
		
		if (facetStyle == FacetStyle.NONE) {
			query.addFacetField(config.getFacetFields().toArray(new String[config.getFacetFields().size()]));
		} else {
			// Add the facet tree params
			query.setFacet(true);
			query.setParam("facet.tree", true);
			query.setParam("facet.tree.field", buildFacetTreeQueryParameter(facetStyle));
		}
		
		LOGGER.debug("Query: {}", query);

		QueryResponse response = server.query(query);
		List<Document> docs;
		long total = 0;
		
		if (response.getGroupResponse() != null) {
			docs = new ArrayList<>(rows);
			GroupResponse gResponse = response.getGroupResponse();
			for (GroupCommand gCommand : gResponse.getValues()) {
				total += gCommand.getNGroups();
				for (Group group : gCommand.getValues()) {
					docs.addAll(server.getBinder().getBeans(Document.class, group.getResult()));
				}
			}
		} else if (response.getResults().getNumFound() == 0) {
			docs = new ArrayList<>();
		} else {
			docs = response.getBeans(Document.class);
			total = response.getResults().getNumFound();
		}
		
		results = new ResultsList<>(docs, start, (start / rows), total, extractFacets(response, facetStyle));
	} catch (SolrServerException e) {
		throw new SearchEngineException(e);
	}

	return results;
}