List of usage examples for org.apache.solr.common SolrDocumentList SolrDocumentList
SolrDocumentList
From source file:org.mousephenotype.cda.solr.service.ExpressionService.java
License:Apache License
private Map<String, SolrDocumentList> getAnatomyToDocsForCategorical(SolrDocumentList response) { Map<String, SolrDocumentList> anatomyToDocs = new HashMap<>(); for (SolrDocument doc : response) { if (doc.containsKey(ObservationDTO.OBSERVATION_TYPE) && doc.get(ObservationDTO.OBSERVATION_TYPE).equals("categorical")) { String anatomy = (String) doc.get(ImageDTO.PARAMETER_NAME); anatomy = anatomy.toLowerCase(); SolrDocumentList anatomyList = null; if (!anatomyToDocs.containsKey(anatomy)) { anatomyToDocs.put(anatomy, new SolrDocumentList()); }//from w ww. j av a 2 s. c o m anatomyList = anatomyToDocs.get(anatomy); anatomyList.add(doc); } } return anatomyToDocs; }
From source file:org.opencms.search.solr.CmsSolrIndex.java
License:Open Source License
/** * Performs the actual search.<p>//from w w w. ja va 2 s .co m * * @param cms the current OpenCms context * @param ignoreMaxRows <code>true</code> to return all all requested rows, <code>false</code> to use max rows * @param query the OpenCms Solr query * @param response the servlet response to write the query result to, may also be <code>null</code> * @param ignoreSearchExclude if set to false, only contents with search_exclude unset or "false" will be found - typical for the the non-gallery case * @param filter the resource filter to use * * @return the found documents * * @throws CmsSearchException if something goes wrong * * @see #search(CmsObject, CmsSolrQuery, boolean) */ @SuppressWarnings("unchecked") public CmsSolrResultList search(CmsObject cms, final CmsSolrQuery query, boolean ignoreMaxRows, ServletResponse response, boolean ignoreSearchExclude, CmsResourceFilter filter) throws CmsSearchException { // check if the user is allowed to access this index checkOfflineAccess(cms); if (!ignoreSearchExclude) { query.addFilterQuery(CmsSearchField.FIELD_SEARCH_EXCLUDE + ":\"false\""); } int previousPriority = Thread.currentThread().getPriority(); long startTime = System.currentTimeMillis(); // remember the initial query SolrQuery initQuery = query.clone(); query.setHighlight(false); LocalSolrQueryRequest solrQueryRequest = null; try { // initialize the search context CmsObject searchCms = OpenCms.initCmsObject(cms); // change thread priority in order to reduce search impact on overall system performance if (getPriority() > 0) { Thread.currentThread().setPriority(getPriority()); } // the lists storing the found documents that will be returned List<CmsSearchResource> resourceDocumentList = new ArrayList<CmsSearchResource>(); SolrDocumentList solrDocumentList = new SolrDocumentList(); // Initialize rows, offset, end and the current page. int rows = query.getRows() != null ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue(); if (!ignoreMaxRows && (rows > ROWS_MAX)) { rows = ROWS_MAX; } int start = query.getStart() != null ? query.getStart().intValue() : 0; int end = start + rows; int page = 0; if (rows > 0) { page = Math.round(start / rows) + 1; } // set the start to '0' and expand the rows before performing the query query.setStart(new Integer(0)); query.setRows(new Integer((5 * rows * page) + start)); // perform the Solr query and remember the original Solr response QueryResponse queryResponse = m_solr.query(query); long solrTime = System.currentTimeMillis() - startTime; // initialize the counts long hitCount = queryResponse.getResults().getNumFound(); start = -1; end = -1; if ((rows > 0) && (page > 0) && (hitCount > 0)) { // calculate the final size of the search result start = rows * (page - 1); end = start + rows; // ensure that both i and n are inside the range of foundDocuments.size() start = new Long((start > hitCount) ? hitCount : start).intValue(); end = new Long((end > hitCount) ? hitCount : end).intValue(); } else { // return all found documents in the search result start = 0; end = new Long(hitCount).intValue(); } long visibleHitCount = hitCount; float maxScore = 0; // If we're using a postprocessor, (re-)initialize it before using it if (m_postProcessor != null) { m_postProcessor.init(); } // process found documents List<CmsSearchResource> allDocs = new ArrayList<CmsSearchResource>(); int cnt = 0; for (int i = 0; (i < queryResponse.getResults().size()) && (cnt < end); i++) { try { SolrDocument doc = queryResponse.getResults().get(i); CmsSolrDocument searchDoc = new CmsSolrDocument(doc); if (needsPermissionCheck(searchDoc)) { // only if the document is an OpenCms internal resource perform the permission check CmsResource resource = filter == null ? getResource(searchCms, searchDoc) : getResource(searchCms, searchDoc, filter); if (resource != null) { // permission check performed successfully: the user has read permissions! if (cnt >= start) { if (m_postProcessor != null) { doc = m_postProcessor.process(searchCms, resource, (SolrInputDocument) searchDoc.getDocument()); } resourceDocumentList.add(new CmsSearchResource(resource, searchDoc)); if (null != doc) { solrDocumentList.add(doc); } maxScore = maxScore < searchDoc.getScore() ? searchDoc.getScore() : maxScore; } allDocs.add(new CmsSearchResource(resource, searchDoc)); cnt++; } else { visibleHitCount--; } } else { // if permission check is not required for this index, // add a pseudo resource together with document to the results resourceDocumentList.add(new CmsSearchResource(PSEUDO_RES, searchDoc)); solrDocumentList.add(doc); maxScore = maxScore < searchDoc.getScore() ? searchDoc.getScore() : maxScore; cnt++; } } catch (Exception e) { // should not happen, but if it does we want to go on with the next result nevertheless LOG.warn(Messages.get().getBundle().key(Messages.LOG_SOLR_ERR_RESULT_ITERATION_FAILED_0), e); } } // the last documents were all secret so let's take the last found docs if (resourceDocumentList.isEmpty() && (allDocs.size() > 0)) { page = Math.round(allDocs.size() / rows) + 1; int showCount = allDocs.size() % rows; showCount = showCount == 0 ? rows : showCount; start = allDocs.size() - new Long(showCount).intValue(); end = allDocs.size(); if (allDocs.size() > start) { resourceDocumentList = allDocs.subList(start, end); for (CmsSearchResource r : resourceDocumentList) { maxScore = maxScore < r.getDocument().getScore() ? r.getDocument().getScore() : maxScore; solrDocumentList.add(((CmsSolrDocument) r.getDocument()).getSolrDocument()); } } } long processTime = System.currentTimeMillis() - startTime - solrTime; // create and return the result solrDocumentList.setStart(start); solrDocumentList.setMaxScore(new Float(maxScore)); solrDocumentList.setNumFound(visibleHitCount); queryResponse.getResponse().setVal(queryResponse.getResponse().indexOf(QUERY_RESPONSE_NAME, 0), solrDocumentList); queryResponse.getResponseHeader().setVal(queryResponse.getResponseHeader().indexOf(QUERY_TIME_NAME, 0), new Integer(new Long(System.currentTimeMillis() - startTime).intValue())); long highlightEndTime = System.currentTimeMillis(); SolrCore core = m_solr instanceof EmbeddedSolrServer ? ((EmbeddedSolrServer) m_solr).getCoreContainer().getCore(getCoreName()) : null; CmsSolrResultList result = null; try { SearchComponent highlightComponenet = null; if (core != null) { highlightComponenet = core.getSearchComponent("highlight"); solrQueryRequest = new LocalSolrQueryRequest(core, queryResponse.getResponseHeader()); } SolrQueryResponse solrQueryResponse = null; if (solrQueryRequest != null) { // create and initialize the solr response solrQueryResponse = new SolrQueryResponse(); solrQueryResponse.setAllValues(queryResponse.getResponse()); int paramsIndex = queryResponse.getResponseHeader().indexOf(HEADER_PARAMS_NAME, 0); NamedList<Object> header = null; Object o = queryResponse.getResponseHeader().getVal(paramsIndex); if (o instanceof NamedList) { header = (NamedList<Object>) o; header.setVal(header.indexOf(CommonParams.ROWS, 0), new Integer(rows)); header.setVal(header.indexOf(CommonParams.START, 0), new Long(start)); } // set the OpenCms Solr query as parameters to the request solrQueryRequest.setParams(initQuery); // perform the highlighting if ((header != null) && (initQuery.getHighlight()) && (highlightComponenet != null)) { header.add(HighlightParams.HIGHLIGHT, "on"); if ((initQuery.getHighlightFields() != null) && (initQuery.getHighlightFields().length > 0)) { header.add(HighlightParams.FIELDS, CmsStringUtil.arrayAsString(initQuery.getHighlightFields(), ",")); } String formatter = initQuery.getParams(HighlightParams.FORMATTER) != null ? initQuery.getParams(HighlightParams.FORMATTER)[0] : null; if (formatter != null) { header.add(HighlightParams.FORMATTER, formatter); } if (initQuery.getHighlightFragsize() != 100) { header.add(HighlightParams.FRAGSIZE, new Integer(initQuery.getHighlightFragsize())); } if (initQuery.getHighlightRequireFieldMatch()) { header.add(HighlightParams.FIELD_MATCH, new Boolean(initQuery.getHighlightRequireFieldMatch())); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(initQuery.getHighlightSimplePost())) { header.add(HighlightParams.SIMPLE_POST, initQuery.getHighlightSimplePost()); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(initQuery.getHighlightSimplePre())) { header.add(HighlightParams.SIMPLE_PRE, initQuery.getHighlightSimplePre()); } if (initQuery.getHighlightSnippets() != 1) { header.add(HighlightParams.SNIPPETS, new Integer(initQuery.getHighlightSnippets())); } ResponseBuilder rb = new ResponseBuilder(solrQueryRequest, solrQueryResponse, Collections.singletonList(highlightComponenet)); try { rb.doHighlights = true; DocListAndSet res = new DocListAndSet(); SchemaField idField = OpenCms.getSearchManager().getSolrServerConfiguration() .getSolrSchema().getUniqueKeyField(); int[] luceneIds = new int[rows]; int docs = 0; for (SolrDocument doc : solrDocumentList) { String idString = (String) doc.getFirstValue(CmsSearchField.FIELD_ID); int id = solrQueryRequest.getSearcher().getFirstMatch( new Term(idField.getName(), idField.getType().toInternal(idString))); luceneIds[docs++] = id; } res.docList = new DocSlice(0, docs, luceneIds, null, docs, 0); rb.setResults(res); rb.setQuery(QParser.getParser(initQuery.getQuery(), null, solrQueryRequest).getQuery()); rb.setQueryString(initQuery.getQuery()); highlightComponenet.prepare(rb); highlightComponenet.process(rb); highlightComponenet.finishStage(rb); } catch (Exception e) { LOG.error(e.getMessage() + " in query: " + initQuery, new Exception(e)); } // Make highlighting also available via the CmsSolrResultList queryResponse.setResponse(solrQueryResponse.getValues()); highlightEndTime = System.currentTimeMillis(); } } result = new CmsSolrResultList(initQuery, queryResponse, solrDocumentList, resourceDocumentList, start, new Integer(rows), end, page, visibleHitCount, new Float(maxScore), startTime, highlightEndTime); if (LOG.isDebugEnabled()) { Object[] logParams = new Object[] { new Long(System.currentTimeMillis() - startTime), new Long(result.getNumFound()), new Long(solrTime), new Long(processTime), new Long(result.getHighlightEndTime() != 0 ? result.getHighlightEndTime() - startTime : 0) }; LOG.debug(query.toString() + "\n" + Messages.get().getBundle().key(Messages.LOG_SOLR_SEARCH_EXECUTED_5, logParams)); } if (response != null) { writeResp(response, solrQueryRequest, solrQueryResponse); } } finally { if (solrQueryRequest != null) { solrQueryRequest.close(); } if (core != null) { core.close(); } } return result; } catch (Exception e) { throw new CmsSearchException(Messages.get().container(Messages.LOG_SOLR_ERR_SEARCH_EXECUTION_FAILD_1, CmsEncoder.decode(query.toString()), e), e); } finally { if (solrQueryRequest != null) { solrQueryRequest.close(); } // re-set thread to previous priority Thread.currentThread().setPriority(previousPriority); } }
From source file:org.opencms.search.solr.CmsSolrIndex.java
License:Open Source License
/** * Executes a spell checking Solr query and returns the Solr query response.<p> * * @param res the servlet response//from ww w . ja v a2 s . co m * @param cms the CMS object * @param q the query * * @throws CmsSearchException if something goes wrong */ public void spellCheck(ServletResponse res, CmsObject cms, CmsSolrQuery q) throws CmsSearchException { SolrCore core = null; LocalSolrQueryRequest solrQueryRequest = null; try { q.setRequestHandler("/spell"); QueryResponse queryResponse = m_solr.query(q); List<CmsSearchResource> resourceDocumentList = new ArrayList<CmsSearchResource>(); SolrDocumentList solrDocumentList = new SolrDocumentList(); if (m_postProcessor != null) { for (int i = 0; (i < queryResponse.getResults().size()); i++) { try { SolrDocument doc = queryResponse.getResults().get(i); CmsSolrDocument searchDoc = new CmsSolrDocument(doc); if (needsPermissionCheck(searchDoc)) { // only if the document is an OpenCms internal resource perform the permission check CmsResource resource = getResource(cms, searchDoc); if (resource != null) { // permission check performed successfully: the user has read permissions! if (m_postProcessor != null) { doc = m_postProcessor.process(cms, resource, (SolrInputDocument) searchDoc.getDocument()); } resourceDocumentList.add(new CmsSearchResource(resource, searchDoc)); solrDocumentList.add(doc); } } } catch (Exception e) { // should not happen, but if it does we want to go on with the next result nevertheless LOG.warn(Messages.get().getBundle().key(Messages.LOG_SOLR_ERR_RESULT_ITERATION_FAILED_0), e); } } queryResponse.getResponse().setVal(queryResponse.getResponse().indexOf(QUERY_RESPONSE_NAME, 0), solrDocumentList); } // create and return the result core = m_solr instanceof EmbeddedSolrServer ? ((EmbeddedSolrServer) m_solr).getCoreContainer().getCore(getCoreName()) : null; SolrQueryResponse solrQueryResponse = new SolrQueryResponse(); solrQueryResponse.setAllValues(queryResponse.getResponse()); // create and initialize the solr request solrQueryRequest = new LocalSolrQueryRequest(core, solrQueryResponse.getResponseHeader()); // set the OpenCms Solr query as parameters to the request solrQueryRequest.setParams(q); writeResp(res, solrQueryRequest, solrQueryResponse); } catch (Exception e) { throw new CmsSearchException( Messages.get().container(Messages.LOG_SOLR_ERR_SEARCH_EXECUTION_FAILD_1, q), e); } finally { if (solrQueryRequest != null) { solrQueryRequest.close(); } if (core != null) { core.close(); } } }
From source file:org.opencommercesearch.RuleManagerTest.java
License:Apache License
@Test public void testSetRuleParamsAndSetFilterQueries() throws RepositoryException, SolrServerException { // make sure that the facetManager gets addFacet called when we supply facets final FacetManager facetManager = mock(FacetManager.class); RuleManager mgr = new RuleManager(repository, builder, server) { @Override// ww w. java 2 s . com public FacetManager getFacetManager() { return facetManager; } }; // we need to make sure that we test filterQueries here... SolrDocumentList solrDocumentList = new SolrDocumentList(); // ---------- set up docs with a rule type ----------- setUpRuleData(null, "description facetRule1", "facetRule1", facetRule, facetRuleItem1, false, solrDocumentList); // note that we do NOT add this into the Repository so that we have a null rule in loadRules, this causes this document to not go into the rules SolrDocument rule = new SolrDocument(); rule.addField("description", "description facetRule2"); rule.addField("id", "facetRule2"); solrDocumentList.add(rule); setUpRuleData(null, "description facetRule3", "facetRule3", boostRule, boostRuleItem1, false, solrDocumentList); // ----------- set up doclist attributes ---------- solrDocumentList.setNumFound(solrDocumentList.size()); solrDocumentList.setStart(0L); // solrDocumentList.setMaxScore(1000.0); when(queryResponse.getResults()).thenReturn(solrDocumentList); when(server.query(any(SolrParams.class))).thenReturn(queryResponse); // ------------ make the call to load the rules etc ------------- RepositoryItem catalog = mock(RepositoryItem.class); when(catalog.getRepositoryId()).thenReturn("bobcatalog"); SolrQuery query = mock(SolrQuery.class); when(query.getQuery()).thenReturn("jackets"); FilterQuery[] filterQueries = new FilterQuery[] { new FilterQuery("category", "jackets"), // is a multi new FilterQuery("category", "12.jackets"), // is a multi new FilterQuery("hasPinStripes", "redstripes"), new FilterQuery("hasFeathers", "socks&stuff"), new FilterQuery("hasLaces", "raingear"), // is a multi new FilterQuery("chopsticks", "lookout below") }; // set up the facet items to catch all conditions RepositoryItem categoryFacetItem = mock(RepositoryItem.class); when(facetManager.getFacetItem("category")).thenReturn(categoryFacetItem); when(categoryFacetItem.getPropertyValue((FacetProperty.IS_MULTI_SELECT))).thenReturn(true); RepositoryItem hasPinStripesFacetItem = mock(RepositoryItem.class); when(facetManager.getFacetItem("hasPinStripes")).thenReturn(hasPinStripesFacetItem); when(hasPinStripesFacetItem.getPropertyValue((FacetProperty.IS_MULTI_SELECT))).thenReturn(false); RepositoryItem hasFeathersFacetItem = mock(RepositoryItem.class); when(facetManager.getFacetItem("hasFeathers")).thenReturn(hasFeathersFacetItem); // don't support multi for hasFeathers... RepositoryItem hasLacesFacetItem = mock(RepositoryItem.class); when(facetManager.getFacetItem("hasLaces")).thenReturn(hasLacesFacetItem); when(hasLacesFacetItem.getPropertyValue((FacetProperty.IS_MULTI_SELECT))).thenReturn(true); // and nothing for chopsticks mgr.setRuleParams(query, true, false, null, filterQueries, catalog, false, null); verify(query).setFacetPrefix("category", "1.bobcatalog."); verify(query).addFilterQuery("category:0.bobcatalog"); verify(query).getQuery(); verify(query, times(2)).getSortFields(); verify(query).setSortField("isToos", ORDER.asc); verify(query).addSortField("score", ORDER.desc); verify(query).addSortField("_version_", ORDER.desc); verify(query).setFacetPrefix("category", "13.jackets."); // verify the single calls to addFilterQuery verify(query).addFilterQuery("hasPinStripes:redstripes"); // this will have a facet verify(query).addFilterQuery("hasFeathers:socks&stuff"); // this will have a facet, but not MULTI verify(query).addFilterQuery("chopsticks:lookout below"); // no facet for this one (test null path) // now verify the multi calls to addFilterQuery verify(query).addFilterQuery("{!tag=category}category:jackets OR category:12.jackets"); verify(query).addFilterQuery("{!tag=hasLaces}hasLaces:raingear"); verify(query).getParams("excludeRules"); verify(query).getParams("includeRules"); verifyNoMoreInteractions(query); }
From source file:org.opencommercesearch.RuleManagerTest.java
License:Apache License
@Test public void testSetRuleParams2NullRules() throws RepositoryException, SolrServerException { SolrDocumentList solrDocumentList = new SolrDocumentList(); setUpRuleData(null, "description facetRule1", "facetRule1", facetRule, facetRuleItem1, false, solrDocumentList);/* w ww .j a v a 2 s .c o m*/ SolrDocument rule = new SolrDocument(); rule.addField("description", "description facetRule2"); rule.addField("id", "facetRule2"); solrDocumentList.add(rule); setUpRuleData(null, "description boostRule3", "boostRule3", boostRule, boostRuleItem1, false, solrDocumentList); solrDocumentList.setNumFound(solrDocumentList.size()); solrDocumentList.setStart(0L); when(queryResponse.getResults()).thenReturn(solrDocumentList); when(server.query(any(SolrParams.class))).thenReturn(queryResponse); RuleManager mgr = new RuleManager(repository, builder, server); assertEquals(null, mgr.getRules()); RepositoryItem catalog = mock(RepositoryItem.class); when(catalog.getRepositoryId()).thenReturn("bobcatalog"); SolrQuery query = mock(SolrQuery.class); when(query.getQuery()).thenReturn("jackets"); mgr.setRuleParams(query, true, false, null, null, catalog, false, null); verify(query).setFacetPrefix("category", "1.bobcatalog."); verify(query).addFilterQuery("category:0.bobcatalog"); verify(query).getQuery(); verify(query, times(2)).getSortFields(); verify(query).setSortField("isToos", ORDER.asc); verify(query).addSortField("score", ORDER.desc); verify(query).addSortField("_version_", ORDER.desc); verify(query).getParams("includeRules"); verify(query).getParams("excludeRules"); verifyNoMoreInteractions(query); }
From source file:org.opencommercesearch.RuleManagerTest.java
License:Apache License
@Test public void testRankingRuleForRuleBasedCategories() throws RepositoryException, SolrServerException { RuleManager mgr = new RuleManager(repository, builder, server); SolrDocumentList ruleList = new SolrDocumentList(); setUpRuleData(null, "description facetRule1", "facetRule1", facetRule, facetRuleItem1, false, ruleList); SolrDocument rule = new SolrDocument(); rule.addField("description", "description facetRule2"); rule.addField("id", "facetRule2"); ruleList.add(rule);//w w w. j a va 2s . c om setUpRuleData(null, "description boostRule1", "boostRule1", boostRule, boostRuleItem1, false, ruleList); List<String> categories = new ArrayList<String>(); categories.add("myCatalog.ruleBasedCategory"); categories.add("__all__"); setUpRuleData(categories, "description boostRule2", "boostRule2", boostRule, boostRuleItem2, false, ruleList); ruleList.setNumFound(ruleList.size()); ruleList.setStart(0L); when(queryResponse.getResults()).thenReturn(ruleList); when(server.query(any(SolrParams.class))).thenReturn(queryResponse); mgr.loadRules("", "myCatalog.ruleBasedCategory", null, false, true, cataA, false, null, new HashSet<String>(), new HashSet<String>()); assertEquals(mgr.getRules().size(), 2); mgr.loadRules("", null, null, false, true, cataA, false, null, new HashSet<String>(), new HashSet<String>()); assertEquals(mgr.getRules().size(), 2); }
From source file:org.opencommercesearch.RuleManagerTest.java
License:Apache License
@Test public void testLoadRulesNullRule() throws RepositoryException, SolrServerException { SolrDocumentList solrDocumentList = new SolrDocumentList(); // ---------- set up docs with a rule type ----------- setUpRuleData(null, "description facetRule1", "facetRule1", facetRule, facetRuleItem1, false, solrDocumentList);/*from w ww.java 2 s . c om*/ // note that we do NOT add this into the Repository so that we have a null rule in loadRules, this causes this document to not go into the rules SolrDocument rule = new SolrDocument(); rule.addField("description", "description facetRule2"); rule.addField("id", "facetRule2"); solrDocumentList.add(rule); setUpRuleData(null, "description boostRule1", "boostRule1", boostRule, boostRuleItem1, false, solrDocumentList); // ----------- set up doclist attributes ---------- solrDocumentList.setNumFound(solrDocumentList.size()); solrDocumentList.setStart(0L); // solrDocumentList.setMaxScore(1000.0); when(queryResponse.getResults()).thenReturn(solrDocumentList); when(server.query(any(SolrParams.class))).thenReturn(queryResponse); // ----------- set up rule manager ------------- RuleManager mgr = new RuleManager(repository, builder, server); assertEquals(null, mgr.getRules()); // ------------ make the call to load the rules etc ------------- mgr.loadRules("jackets", null, "Men's Clothing", true, false, cataA, false, null, new HashSet<String>(), new HashSet<String>()); // ------------ assertions about the rules that were generated --------- assertNotNull(mgr.getRules()); Map<String, List<RepositoryItem>> rules = mgr.getRules(); assertEquals(2, rules.size()); assertThat(rules.keySet(), hasItem(facetRule)); assertThat(rules.keySet(), hasItem(boostRule)); List<RepositoryItem> facetItems = rules.get(facetRule); List<RepositoryItem> boostItems = rules.get(boostRule); assertEquals(1, facetItems.size()); assertEquals(1, boostItems.size()); assertThat(facetItems, hasItem(facetRuleItem1)); assertThat(boostItems, hasItem(boostRuleItem1)); }
From source file:org.opencommercesearch.RuleManagerTest.java
License:Apache License
@Test public void testLoadRulesMixedTypes() throws RepositoryException, SolrServerException { SolrDocumentList solrDocumentList = new SolrDocumentList(); // ---------- set up docs with a rule type ----------- setUpRuleData(null, "description facetRule1", "facetRule1", facetRule, facetRuleItem1, false, solrDocumentList);/* w ww .j a va 2s . c o m*/ setUpRuleData(null, "description blockRule1", "blockRule1", blockRule, blockRuleItem1, false, solrDocumentList); setUpRuleData(null, "description boostRule1", "boostRule1", boostRule, boostRuleItem1, false, solrDocumentList); // ----------- set up doclist attributes ---------- solrDocumentList.setNumFound(solrDocumentList.size()); solrDocumentList.setStart(0L); // solrDocumentList.setMaxScore(1000.0); when(queryResponse.getResults()).thenReturn(solrDocumentList); when(server.query(any(SolrParams.class))).thenReturn(queryResponse); // ----------- set up rule manager ------------- RuleManager mgr = new RuleManager(repository, builder, server); assertEquals(null, mgr.getRules()); // ------------ make the call to load the rules etc ------------- mgr.loadRules("jackets", null, "Men's Clothing", true, false, cataA, false, null, new HashSet<String>(), new HashSet<String>()); // ------------ assertions about the rules that were generated --------- assertNotNull(mgr.getRules()); Map<String, List<RepositoryItem>> rules = mgr.getRules(); assertEquals(3, rules.size()); assertThat(rules.keySet(), hasItem(facetRule)); assertThat(rules.keySet(), hasItem(boostRule)); assertThat(rules.keySet(), hasItem(blockRule)); List<RepositoryItem> facetItems = rules.get(facetRule); List<RepositoryItem> boostItems = rules.get(boostRule); List<RepositoryItem> blockItems = rules.get(blockRule); assertEquals(1, facetItems.size()); assertEquals(1, boostItems.size()); assertEquals(1, blockItems.size()); assertThat(facetItems, hasItem(facetRuleItem1)); assertThat(boostItems, hasItem(boostRuleItem1)); assertThat(blockItems, hasItem(blockRuleItem1)); }
From source file:org.opencommercesearch.RuleManagerTest.java
License:Apache License
@Test public void testLoadRulesPaging() throws RepositoryException, SolrServerException { // test paging over batches of results SolrDocumentList docList1 = new SolrDocumentList(); SolrDocumentList docList2 = new SolrDocumentList(); RepositoryItem bikeItem = mock(RepositoryItem.class); RepositoryItem sledItem = mock(RepositoryItem.class); RepositoryItem carItem = mock(RepositoryItem.class); RepositoryItem heliItem = mock(RepositoryItem.class); RepositoryItem coatItem = mock(RepositoryItem.class); RepositoryItem snowItem = mock(RepositoryItem.class); RepositoryItem farmItem = mock(RepositoryItem.class); RepositoryItem steakItem = mock(RepositoryItem.class); RepositoryItem pillowItem = mock(RepositoryItem.class); // ---------- set up docs with a rule type ----------- setUpRuleData(null, "description facetRule1", "facetRule1", facetRule, facetRuleItem1, false, docList1); // SKIPPING due to setStart setUpRuleData(null, "description blockRule1", "blockRule1", blockRule, blockRuleItem1, false, docList1); setUpRuleData(null, "description boostRule1", "boostRule1", boostRule, boostRuleItem1, false, docList1); setUpRuleData(null, "biking? fun!", "tallboy", boostRule, bikeItem, false, docList1); setUpRuleData(null, "sleds are lame", "suzuki", facetRule, sledItem, false, docList1); setUpRuleData(null, "cars are lame", "vw", facetRule, carItem, false, docList1); setUpRuleData(null, "fly in a heli", "heli", boostRule, heliItem, false, docList2); // SKIPPING due to setStart setUpRuleData(null, "snow is fun", "snow", boostRule, snowItem, false, docList2); setUpRuleData(null, "good for food", "farm", blockRule, farmItem, false, docList2); setUpRuleData(null, "cows are food", "steak", facetRule, steakItem, false, docList2); setUpRuleData(null, "coatItem", "patagonia", boostRule, coatItem, false, docList2); setUpRuleData(null, "sleeping", "pillow", boostRule, pillowItem, false, docList2); // ----------- set up doclist attributes ---------- docList1.setNumFound(docList1.size() + docList2.size()); // set numfound to be both pagefuls... docList2.setNumFound(docList1.size() + docList2.size()); // set numfound to be both pagefuls... docList1.setStart(0L);/*from w w w. ja v a 2 s . c om*/ docList2.setStart(0L); // solrDocumentList.setMaxScore(1000.0); QueryResponse queryResponse1 = mock(QueryResponse.class); QueryResponse queryResponse2 = mock(QueryResponse.class); when(queryResponse1.getResults()).thenReturn(docList1); when(queryResponse2.getResults()).thenReturn(docList2); // when(server.query(any(SolrParams.class))).thenReturn(queryResponse); when(server.query(any(SolrParams.class))).thenReturn(queryResponse1, queryResponse2); // ----------- set up rule manager ------------- RuleManager mgr = new RuleManager(repository, builder, server); assertEquals(null, mgr.getRules()); // ------------ make the call to load the rules etc ------------- mgr.loadRules("jackets", null, "Men's Clothing", true, false, cataA, false, null, new HashSet<String>(), new HashSet<String>()); // ------------ assertions about the rules that were generated --------- assertNotNull(mgr.getRules()); Map<String, List<RepositoryItem>> rules = mgr.getRules(); assertEquals(3, rules.size()); assertThat(rules.keySet(), hasItem(facetRule)); assertThat(rules.keySet(), hasItem(boostRule)); assertThat(rules.keySet(), hasItem(blockRule)); List<RepositoryItem> facetItems = rules.get(facetRule); List<RepositoryItem> boostItems = rules.get(boostRule); List<RepositoryItem> blockItems = rules.get(blockRule); assertEquals(4, facetItems.size()); assertEquals(6, boostItems.size()); assertEquals(2, blockItems.size()); // test facets... for (RepositoryItem item : new RepositoryItem[] { sledItem, carItem, steakItem, }) { assertThat(facetItems, hasItem(item)); } // test boosts... for (RepositoryItem item : new RepositoryItem[] { boostRuleItem1, bikeItem, snowItem, coatItem, pillowItem, }) { assertThat(boostItems, hasItem(item)); } // test blocks... for (RepositoryItem item : new RepositoryItem[] { blockRuleItem1, farmItem, }) { assertThat(blockItems, hasItem(item)); } }
From source file:org.opencommercesearch.RuleManagerTest.java
License:Apache License
@Test public void testLoadRulesFacets() throws RepositoryException, SolrServerException { SolrDocumentList solrDocumentList = new SolrDocumentList(); // ---------- set up docs with a rule type ----------- setUpRuleData(null, "description facetRule1", "facetRule1", facetRule, facetRuleItem1, false, solrDocumentList);//from w w w . j a v a2 s. c o m setUpRuleData(null, "description facetRule2", "facetRule2", facetRule, blockRuleItem1, false, solrDocumentList); setUpRuleData(null, "description facetRule3", "facetRule3", facetRule, boostRuleItem1, false, solrDocumentList); // ----------- set up doclist attributes ---------- solrDocumentList.setNumFound(solrDocumentList.size()); solrDocumentList.setStart(0L); // solrDocumentList.setMaxScore(1000.0); when(queryResponse.getResults()).thenReturn(solrDocumentList); when(server.query(any(SolrParams.class))).thenReturn(queryResponse); // ----------- set up rule manager ------------- RuleManager mgr = new RuleManager(repository, builder, server); assertEquals(null, mgr.getRules()); // ------------ make the call to load the rules etc ------------- mgr.loadRules("jackets", null, "Men's Clothing", true, false, cataA, false, null, new HashSet<String>(), new HashSet<String>()); // ------------ assertions about the rules that were generated --------- assertNotNull(mgr.getRules()); Map<String, List<RepositoryItem>> rules = mgr.getRules(); assertEquals(1, rules.size()); assertEquals(facetRule, rules.keySet().iterator().next()); List<RepositoryItem> facetItems = rules.get(facetRule); assertEquals(3, facetItems.size()); assertThat(facetItems, hasItem(facetRuleItem1)); assertThat(facetItems, hasItem(blockRuleItem1)); assertThat(facetItems, hasItem(boostRuleItem1)); }