List of usage examples for org.apache.solr.common SolrDocumentList getNumFound
public long getNumFound()
From source file:org.seedstack.solr.SolrIT.java
License:Mozilla Public License
@Test public void index_and_join_search_two_different_embedded_collection() throws SolrServerException, IOException { addDocuments1();/*ww w. j a va2s . co m*/ try { addDocuments2(); try { QueryResponse queryResponse = transactional_multicore_query(); SolrDocumentList docs = queryResponse.getResults(); assertThat(docs).isNotNull(); assertThat(docs.getNumFound()).isEqualTo(1); } finally { clean2(); } } finally { clean1(); } }
From source file:org.seedstack.solr.SolrIT.java
License:Mozilla Public License
@Test public void query_without_transaction() throws SolrServerException, IOException { addDocuments1();//from w w w . j ava 2 s . c o m try { QueryResponse queryResponse = solrClient1.query(new SolrQuery("name:Gerard")); SolrDocumentList docs = queryResponse.getResults(); assertThat(docs).isNotNull(); assertThat(docs.getNumFound()).isEqualTo(1); } finally { clean1(); } }
From source file:org.segrada.search.solr.SolrSearchEngine.java
License:Apache License
@Override public PaginationInfo<SearchHit> search(String searchTerm, Map<String, String> filters) { // to avoid NPEs if (filters == null) filters = new HashMap<>(); // set defaults int page = 1; int entriesPerPage = 20; try {/*from w w w. jav a2s . c o m*/ // Parse a simple query that searches for "text": MultiFieldQueryParser parser; String[] containFields; // do we have a filter to contain to certain fields? if (filters.containsKey("fields")) { String fields = filters.get("fields"); if (fields.isEmpty()) containFields = new String[] { this.title, this.subTitles, this.content }; else if (fields.equalsIgnoreCase(this.title)) containFields = new String[] { this.title }; else if (fields.equalsIgnoreCase(this.subTitles)) containFields = new String[] { this.subTitles }; else if (fields.equalsIgnoreCase(this.content)) containFields = new String[] { this.content }; else if (fields.equalsIgnoreCase("allTitles")) containFields = new String[] { this.title, this.subTitles }; else throw new RuntimeException("fields-Filter " + fields + " is not known."); } else containFields = new String[] { this.title, this.subTitles, this.content }; parser = new MultiFieldQueryParser(Version.LUCENE_47, containFields, analyzer); // which operator do we use? parser.setDefaultOperator(QueryParser.Operator.AND); if (filters.containsKey("operator")) { String operator = filters.get("operator"); if (operator.equalsIgnoreCase("or")) parser.setDefaultOperator(QueryParser.Operator.OR); else if (!operator.isEmpty() && !operator.equalsIgnoreCase("and")) throw new RuntimeException("operator-Filter " + operator + " is not and/or."); } // filters for query SolrQuery query = new SolrQuery(); // class filter if (filters.containsKey("class") && !filters.get("class").isEmpty()) { // multiple classes? String[] classes = filters.get("class").split(","); // single class if (classes.length <= 1) { query.addFilterQuery(this.className, filters.get("class")); } else { // multiple classes StringBuilder chained = new StringBuilder("("); for (int i = 0; i < classes.length; i++) { if (i > 0) chained.append(" OR "); chained.append("className:").append(classes[i].trim()); } query.addFilterQuery(this.className, chained + ")"); } } // tag filter if (filters.containsKey("tags") && !filters.get("tags").isEmpty()) { // split tags into array String[] tags = filters.get("tags").split(","); BooleanQuery booleanQuery = new BooleanQuery(); for (String tagLocal : tags) { booleanQuery.add(new TermQuery(new Term("tag", tagLocal.trim())), BooleanClause.Occur.SHOULD); } query.addFilterQuery(this.tag, booleanQuery.toString()); } // define query Query queryTerm = null; if (searchTerm != null) queryTerm = parser.parse(searchTerm); if (queryTerm == null) queryTerm = new MatchAllDocsQuery(); // fallback to match all documents query.setQuery(queryTerm.toString()); // get hits per page if (filters.containsKey("limit")) { try { entriesPerPage = Integer.valueOf(filters.get("limit")); if (entriesPerPage <= 0 || entriesPerPage > 1000) entriesPerPage = 20; } catch (NumberFormatException e) { logger.warn("Could not parse limit " + filters.get("limit") + " to integer", e); } } // get page number if (filters.containsKey("page")) { try { page = Integer.valueOf(filters.get("page")); } catch (NumberFormatException e) { logger.warn("Could not parse page " + filters.get("page") + " to integer", e); } } // calculate start index int startIndex = (page - 1) * entriesPerPage; query.setStart(startIndex); query.setRows(entriesPerPage); query.setFields("*", "score"); // define highlighting query.setHighlight(true); query.addHighlightField(this.content); query.setHighlightFragsize(18); query.setHighlightSnippets(10); query.setHighlightSimplePre("<b>"); query.setHighlightSimplePost("</b>"); // do query QueryResponse response = solr.query(query); SolrDocumentList results = response.getResults(); // how many pages do we have? int pages = (int) (results.getNumFound() / entriesPerPage + 1); // cycle trough hits List<SearchHit> hits = new ArrayList<>(); for (SolrDocument doc : results) { SearchHit searchHit = createHitFromDocument(doc); // add score Object score = doc.get("score"); if (score != null && score instanceof Float) searchHit.setRelevance((float) score); // get highlighted components if (searchTerm != null && response.getHighlighting().get(searchHit.getId()) != null) { List<String> fragments = response.getHighlighting().get(searchHit.getId()).get(this.content); if (fragments != null) { String[] bestFragments = new String[fragments.size() > 10 ? 10 : fragments.size()]; for (int i = 0; i < bestFragments.length; i++) bestFragments[i] = fragments.get(i); searchHit.setHighlightText(bestFragments); } } // add hit hits.add(searchHit); } // return pagination info return new PaginationInfo<>(page, pages, (int) results.getNumFound(), entriesPerPage, hits); } catch (Throwable e) { logger.error("Error in search.", e); } // return empty list result in order to avoid NPEs return new PaginationInfo<>(page, 1, 0, entriesPerPage, new ArrayList<>()); }
From source file:org.sindice.siren.solr.TestSirenQParserPlugin.java
License:Apache License
/** * SRN-96/*w w w. java 2 s . co m*/ */ @Test public void testASCIIFoldingExpansion() throws IOException, SolrServerException { this.addNTripleString("id1", "<http://s> <http://p> \"cafe\" ."); this.addNTripleString("id2", "<http://s> <http://p> \"caf\" ."); SolrQuery query = new SolrQuery(); query.setQuery("cafe"); query.setQueryType("siren"); query.setIncludeScore(true); // should match the two documents, with same score QueryResponse response = wrapper.server.query(query); SolrDocumentList docList = response.getResults(); assertEquals(2, docList.getNumFound()); float score1 = (Float) docList.get(0).getFieldValue("score"); float score2 = (Float) docList.get(1).getFieldValue("score"); Assert.assertTrue("Score should be identical", score1 == score2); query = new SolrQuery(); query.setQueryType("siren"); query.set(SirenParams.NQ, "* * 'cafe'"); query.setIncludeScore(true); // should match the two documents, with same score response = wrapper.server.query(query); docList = response.getResults(); assertEquals(2, docList.getNumFound()); score1 = (Float) docList.get(0).getFieldValue("score"); score2 = (Float) docList.get(1).getFieldValue("score"); Assert.assertTrue("Score should be identical", score1 == score2); // should match the two documents, but should assign different score // id2 should receive better score than id1 query = new SolrQuery(); query.setQuery("caf"); query.setQueryType("siren"); query.setIncludeScore(true); response = wrapper.server.query(query); docList = response.getResults(); assertEquals(2, docList.getNumFound()); if (docList.get(0).getFieldValue("url").equals("id1")) { score1 = (Float) docList.get(0).getFieldValue("score"); score2 = (Float) docList.get(1).getFieldValue("score"); } else { score2 = (Float) docList.get(0).getFieldValue("score"); score1 = (Float) docList.get(1).getFieldValue("score"); } Assert.assertTrue("id2 should get higher score than id1", score1 < score2); query = new SolrQuery(); query.setQueryType("siren"); query.set(SirenParams.NQ, "* * 'caf'"); query.setIncludeScore(true); response = wrapper.server.query(query); System.out.println(response); docList = response.getResults(); assertEquals(2, docList.getNumFound()); if (docList.get(0).getFieldValue("url").equals("id1")) { score1 = (Float) docList.get(0).getFieldValue("score"); score2 = (Float) docList.get(1).getFieldValue("score"); } else { score2 = (Float) docList.get(0).getFieldValue("score"); score1 = (Float) docList.get(1).getFieldValue("score"); } Assert.assertTrue("id2 should get higher score than id1", score1 < score2); }
From source file:org.sleuthkit.autopsy.keywordsearch.LuceneQuery.java
License:Open Source License
/** * Perform the query and return results of unique files. * * @param snippets True if results should have a snippet * @return list of ContentHit objects. One per file with hit (ignores * multiple hits of the word in the same doc) * @throws NoOpenCoreException//from ww w. j a v a 2s .c o m */ private List<KeywordHit> performLuceneQuery(boolean snippets) throws NoOpenCoreException { List<KeywordHit> matches = new ArrayList<>(); boolean allMatchesFetched = false; final Server solrServer = KeywordSearch.getServer(); SolrQuery q = createAndConfigureSolrQuery(snippets); // cycle through results in sets of MAX_RESULTS for (int start = 0; !allMatchesFetched; start = start + MAX_RESULTS) { q.setStart(start); try { QueryResponse response = solrServer.query(q, METHOD.POST); SolrDocumentList resultList = response.getResults(); // objectId_chunk -> "text" -> List of previews Map<String, Map<String, List<String>>> highlightResponse = response.getHighlighting(); // get the unique set of files with hits Set<SolrDocument> uniqueSolrDocumentsWithHits = filterDuplicateSolrDocuments(resultList); allMatchesFetched = start + MAX_RESULTS >= resultList.getNumFound(); SleuthkitCase sleuthkitCase; try { sleuthkitCase = Case.getCurrentCase().getSleuthkitCase(); } catch (IllegalStateException ex) { //no case open, must be just closed return matches; } for (SolrDocument resultDoc : uniqueSolrDocumentsWithHits) { KeywordHit contentHit; try { contentHit = createKeywordtHit(resultDoc, highlightResponse, sleuthkitCase); } catch (TskException ex) { return matches; } matches.add(contentHit); } } catch (NoOpenCoreException ex) { logger.log(Level.WARNING, "Error executing Lucene Solr Query: " + keywordString, ex); //NON-NLS throw ex; } catch (KeywordSearchModuleException ex) { logger.log(Level.WARNING, "Error executing Lucene Solr Query: " + keywordString, ex); //NON-NLS } } return matches; }
From source file:org.springframework.data.solr.core.ResultHelper.java
License:Apache License
static <T> Map<Object, GroupResult<T>> convertGroupQueryResponseToGroupResultMap(Query query, Map<String, Object> objectNames, QueryResponse response, SolrTemplate solrTemplate, Class<T> clazz) { GroupResponse groupResponse = response.getGroupResponse(); if (groupResponse == null) { return Collections.emptyMap(); }//from www . j a va2 s . c om Map<Object, GroupResult<T>> result = new LinkedHashMap<Object, GroupResult<T>>(); List<GroupCommand> values = groupResponse.getValues(); for (GroupCommand groupCommand : values) { List<GroupEntry<T>> groupEntries = new ArrayList<GroupEntry<T>>(); for (Group group : groupCommand.getValues()) { SolrDocumentList documentList = group.getResult(); List<T> beans = solrTemplate.convertSolrDocumentListToBeans(documentList, clazz); Page<T> page = new PageImpl<T>(beans, query.getGroupOptions().getPageRequest(), documentList.getNumFound()); groupEntries.add(new SimpleGroupEntry<T>(group.getGroupValue(), page)); } int matches = groupCommand.getMatches(); Integer ngroups = groupCommand.getNGroups(); String name = groupCommand.getName(); PageImpl<GroupEntry<T>> page; if (ngroups != null) { page = new PageImpl<GroupEntry<T>>(groupEntries, query.getPageRequest(), ngroups.intValue()); } else { page = new PageImpl<GroupEntry<T>>(groupEntries); } SimpleGroupResult<T> groupResult = new SimpleGroupResult<T>(matches, ngroups, name, page); result.put(name, groupResult); if (objectNames.containsKey(name)) { result.put(objectNames.get(name), groupResult); } } return result; }
From source file:org.springframework.data.solr.core.ResultHelperTests.java
License:Apache License
/** * @see DATASOLR-121/*from w w w . j a v a 2 s. com*/ */ @Test public void testConvertGroupQueryResponseToGroupResultList() { GroupResponse groupResponse = Mockito.mock(GroupResponse.class); Query query = Mockito.mock(Query.class); SolrTemplate solrTemplate = Mockito.mock(SolrTemplate.class); GroupCommand groupCommand1 = Mockito.mock(GroupCommand.class); Group group1_1 = Mockito.mock(Group.class); SolrDocumentList group1_1DocumentList = Mockito.mock(SolrDocumentList.class); List<Object> documents1_1 = Arrays.asList(new Object()); Mockito.when(response.getGroupResponse()).thenReturn(groupResponse); Mockito.when(groupResponse.getValues()).thenReturn(Arrays.asList(groupCommand1)); Mockito.when(groupCommand1.getValues()).thenReturn(Arrays.asList(group1_1)); Mockito.when(group1_1.getResult()).thenReturn(group1_1DocumentList); Mockito.when(group1_1.getGroupValue()).thenReturn("group1_1_value"); Mockito.when(group1_1DocumentList.getNumFound()).thenReturn(3L); Mockito.when(solrTemplate.convertSolrDocumentListToBeans(group1_1DocumentList, Object.class)) .thenReturn(documents1_1); Mockito.when(groupCommand1.getMatches()).thenReturn(1); Mockito.when(groupCommand1.getName()).thenReturn("group1_name"); Mockito.when(groupCommand1.getNGroups()).thenReturn(2); GroupOptions groupOptions = new GroupOptions(); groupOptions.setLimit(1); Mockito.when(query.getPageRequest()).thenReturn(new PageRequest(0, 1)); Mockito.when(query.getGroupOptions()).thenReturn(groupOptions); Object group1Key = new Object(); Map<String, Object> objectNames = new HashMap<String, Object>(); objectNames.put("group1_name", group1Key); Map<Object, GroupResult<Object>> result = ResultHelper.convertGroupQueryResponseToGroupResultMap(query, objectNames, response, solrTemplate, Object.class); Assert.assertNotNull(result); Assert.assertEquals(2, result.size()); GroupResult<Object> groupResult = result.get("group1_name"); Assert.assertEquals(groupResult, result.get(group1Key)); Assert.assertEquals("group1_name", groupResult.getName()); Assert.assertEquals(1, groupResult.getMatches()); Assert.assertEquals(Integer.valueOf(2), groupResult.getGroupsCount()); Page<GroupEntry<Object>> groupEntries = groupResult.getGroupEntries(); Assert.assertEquals(2, groupEntries.getTotalElements()); Assert.assertEquals(2, groupEntries.getTotalPages()); Assert.assertEquals(true, groupEntries.hasNext()); List<GroupEntry<Object>> groupEntriesContent = groupEntries.getContent(); Assert.assertNotNull(groupEntriesContent); Assert.assertEquals(1, groupEntriesContent.size()); GroupEntry<Object> groupEntriesContentElement = groupEntriesContent.get(0); Assert.assertEquals("group1_1_value", groupEntriesContentElement.getGroupValue()); Page<Object> group1result = groupEntriesContentElement.getResult(); Assert.assertEquals(3, group1result.getTotalElements()); Assert.assertEquals(3, group1result.getTotalPages()); Assert.assertEquals(true, group1result.hasNext()); }
From source file:org.springframework.data.solr.core.ResultHelperTests.java
License:Apache License
/** * @see DATASOLR-121/*from w w w . j a v a 2 s . c om*/ */ @Test public void testConvertGroupQueryResponseToGroupResultListWhenNoCountOfGroups() { GroupResponse groupResponse = Mockito.mock(GroupResponse.class); Query query = Mockito.mock(Query.class); SolrTemplate solrTemplate = Mockito.mock(SolrTemplate.class); GroupCommand groupCommand1 = Mockito.mock(GroupCommand.class); Group group1_1 = Mockito.mock(Group.class); SolrDocumentList group1_1DocumentList = Mockito.mock(SolrDocumentList.class); List<Object> documents1_1 = Arrays.asList(new Object()); Mockito.when(response.getGroupResponse()).thenReturn(groupResponse); Mockito.when(groupResponse.getValues()).thenReturn(Arrays.asList(groupCommand1)); Mockito.when(groupCommand1.getValues()).thenReturn(Arrays.asList(group1_1)); Mockito.when(group1_1.getResult()).thenReturn(group1_1DocumentList); Mockito.when(group1_1.getGroupValue()).thenReturn("group1_1_value"); Mockito.when(group1_1DocumentList.getNumFound()).thenReturn(3L); Mockito.when(solrTemplate.convertSolrDocumentListToBeans(group1_1DocumentList, Object.class)) .thenReturn(documents1_1); Mockito.when(groupCommand1.getMatches()).thenReturn(1); Mockito.when(groupCommand1.getName()).thenReturn("group1_name"); Mockito.when(groupCommand1.getNGroups()).thenReturn(null); GroupOptions groupOptions = new GroupOptions(); groupOptions.setLimit(1); Mockito.when(query.getPageRequest()).thenReturn(new PageRequest(0, 1)); Mockito.when(query.getGroupOptions()).thenReturn(groupOptions); Object group1Key = new Object(); Map<String, Object> objectNames = new HashMap<String, Object>(); objectNames.put("group1_name", group1Key); Map<Object, GroupResult<Object>> result = ResultHelper.convertGroupQueryResponseToGroupResultMap(query, objectNames, response, solrTemplate, Object.class); Assert.assertNotNull(result); Assert.assertEquals(2, result.size()); GroupResult<Object> groupResult = result.get("group1_name"); Assert.assertEquals(result.get(group1Key), groupResult); Assert.assertEquals("group1_name", groupResult.getName()); Assert.assertEquals(1, groupResult.getMatches()); Assert.assertEquals(null, groupResult.getGroupsCount()); Page<GroupEntry<Object>> groupEntries = groupResult.getGroupEntries(); Assert.assertEquals(1, groupEntries.getTotalElements()); Assert.assertEquals(1, groupEntries.getTotalPages()); Assert.assertEquals(false, groupEntries.hasNext()); List<GroupEntry<Object>> groupEntriesContent = groupEntries.getContent(); Assert.assertNotNull(groupEntriesContent); Assert.assertEquals(1, groupEntriesContent.size()); GroupEntry<Object> groupEntriesContentElement = groupEntriesContent.get(0); Assert.assertEquals("group1_1_value", groupEntriesContentElement.getGroupValue()); Page<Object> group1result = groupEntriesContentElement.getResult(); Assert.assertEquals(3, group1result.getTotalElements()); Assert.assertEquals(3, group1result.getTotalPages()); Assert.assertEquals(true, group1result.hasNext()); }
From source file:org.springframework.data.solr.core.SolrTemplateMulticoreTests.java
License:Apache License
@Test public void testCountQueries() throws SolrServerException, IOException { ArgumentCaptor<SolrQuery> captor1 = ArgumentCaptor.forClass(SolrQuery.class); ArgumentCaptor<SolrQuery> captor2 = ArgumentCaptor.forClass(SolrQuery.class); QueryResponse response1Mock = Mockito.mock(QueryResponse.class); SolrDocumentList resultList1 = new SolrDocumentList(); resultList1.setNumFound(10);//from www . jav a2 s .c om Mockito.when(response1Mock.getResults()).thenReturn(resultList1); QueryResponse response2Mock = Mockito.mock(QueryResponse.class); SolrDocumentList resultList2 = new SolrDocumentList(); resultList2.setNumFound(10); Mockito.when(response2Mock.getResults()).thenReturn(resultList2); Mockito.when(core1Client.query(Mockito.any(SolrQuery.class), Mockito.eq(SolrRequest.METHOD.GET))) .thenReturn(response1Mock); Mockito.when(core2Client.query(Mockito.any(SolrQuery.class), Mockito.eq(SolrRequest.METHOD.GET))) .thenReturn(response2Mock); long result1 = solrTemplate.count("core1", new SimpleQuery(new Criteria("field_1").is("value1"))); long result2 = solrTemplate.count("core2", new SimpleQuery(new Criteria("field_2").is("value2"))); assertEquals(resultList1.getNumFound(), result1); assertEquals(resultList2.getNumFound(), result2); Mockito.verify(core1Client, Mockito.times(1)).query(captor1.capture(), Mockito.eq(SolrRequest.METHOD.GET)); Mockito.verify(core2Client, Mockito.times(1)).query(captor2.capture(), Mockito.eq(SolrRequest.METHOD.GET)); }
From source file:org.springframework.data.solr.core.SolrTemplateTest.java
License:Apache License
@Test public void testCount() throws SolrServerException { ArgumentCaptor<SolrQuery> captor = ArgumentCaptor.forClass(SolrQuery.class); QueryResponse responseMock = Mockito.mock(QueryResponse.class); SolrDocumentList resultList = new SolrDocumentList(); resultList.setNumFound(10);/*from w w w. ja v a 2 s . c o m*/ Mockito.when(responseMock.getResults()).thenReturn(resultList); Mockito.when(solrServerMock.query(Mockito.any(SolrQuery.class))).thenReturn(responseMock); long result = solrTemplate.count(new SimpleQuery(new Criteria("field_1").is("value1"))); Assert.assertEquals(resultList.getNumFound(), result); Mockito.verify(solrServerMock, Mockito.times(1)).query(captor.capture()); Assert.assertEquals(Integer.valueOf(0), captor.getValue().getStart()); Assert.assertEquals(Integer.valueOf(0), captor.getValue().getRows()); }