Java Code Examples for org.apache.solr.client.solrj.SolrQuery#addFacetField()
The following examples show how to use
org.apache.solr.client.solrj.SolrQuery#addFacetField() .
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: DefaultQueryParser.java From dubbox with Apache License 2.0 | 6 votes |
private void appendFacetingOnFields(SolrQuery solrQuery, FacetQuery query) { FacetOptions facetOptions = query.getFacetOptions(); solrQuery.addFacetField(convertFieldListToStringArray(facetOptions.getFacetOnFields())); if (facetOptions.hasFacetPrefix()) { solrQuery.setFacetPrefix(facetOptions.getFacetPrefix()); } for (FacetOptions.FieldWithFacetParameters parametrizedField : facetOptions.getFieldsWithParameters()) { addPerFieldFacetParameters(solrQuery, parametrizedField); if (parametrizedField.getSort() != null && FacetOptions.FacetSort.INDEX.equals(parametrizedField.getSort())) { addFieldSpecificParameterToSolrQuery(solrQuery, parametrizedField, new FacetParameter(FacetParams.FACET_SORT, FacetParams.FACET_SORT_INDEX)); } } }
Example 2
Source File: TestBulkSchemaAPI.java From lucene-solr with Apache License 2.0 | 6 votes |
@Test public void testAddNewFieldAndQuery() throws Exception { getSolrClient().add(Arrays.asList( sdoc("id", "1", "term_s", "tux"))); getSolrClient().commit(true, true); Map<String,Object> attrs = new HashMap<>(); attrs.put("name", "newstringtestfield"); attrs.put("type", "string"); new SchemaRequest.AddField(attrs).process(getSolrClient()); SolrQuery query = new SolrQuery("*:*"); query.addFacetField("newstringtestfield"); int size = getSolrClient().query(query).getResults().size(); assertEquals(1, size); }
Example 3
Source File: ItemSearchServiceLiveTest.java From tutorials with MIT License | 6 votes |
@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 4
Source File: SolrQueryUtil.java From scipio-erp with Apache License 2.0 | 5 votes |
public static void addFacetFields(SolrQuery solrQuery, Collection<String> facetFields) { if (facetFields != null) { for(String facetField : facetFields) { solrQuery.addFacetField(facetField); } } }
Example 5
Source File: BasicDistributedZkTest.java From lucene-solr with Apache License 2.0 | 5 votes |
private void testSortableTextFaceting() throws Exception { SolrQuery query = new SolrQuery("*:*"); query.addFacetField(tsort); query.setFacetMissing(false); QueryResponse resp = queryServer(query); List<FacetField> ffs = resp.getFacetFields(); for (FacetField ff : ffs) { if (ff.getName().equals(tsort) == false) continue; for (FacetField.Count count : ff.getValues()) { long num = count.getCount(); switch (count.getName()) { case "all the kings horses and all the kings men": case "An eye for eye only ends up making the whole world blind.": case "Great works are performed, not by strength, but by perseverance.": case "how now brown cow": case "no eggs on wall, lesson learned": case "now is the time for all good men": case "this too shall pass": case "to come to the aid of their country.": assertEquals("Should have exactly one facet count for field " + ff.getName(), 1, num); break; case "the quick fox jumped over the lazy dog": assertEquals("Should have 5 docs for the lazy dog", 5, num); break; default: fail("No case for facet '" + ff.getName() + "'"); } } } }
Example 6
Source File: SolrProductSearch.java From scipio-erp with Apache License 2.0 | 4 votes |
/** * 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 7
Source File: TestTolerantSearch.java From lucene-solr with Apache License 2.0 | 4 votes |
@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 8
Source File: TestTolerantSearch.java From lucene-solr with Apache License 2.0 | 4 votes |
@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 9
Source File: SearchITCase.java From apache-solr-essentials with Apache License 2.0 | 4 votes |
/** * 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 10
Source File: SolrDocumentSearch.java From BioSolr with Apache License 2.0 | 4 votes |
@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; }