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

The following examples show how to use org.apache.solr.client.solrj.SolrQuery#set() . 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: MCROAISolrSearcher.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
protected MCROAISolrResult solrQuery(Optional<String> cursor) throws SolrServerException, IOException {
    SolrQuery query = getBaseQuery(CommonParams.Q);

    // set support
    if (this.set != null) {
        String setId = this.set.getSetId();
        MCROAISetConfiguration<SolrQuery, SolrDocument, String> setConfig = getSetManager().getConfig(setId);
        setConfig.getHandler().apply(this.set, query);
    }
    // from & until
    if (this.from != null || this.until != null) {
        String fromUntilCondition = buildFromUntilCondition(this.from, this.until);
        query.add(CommonParams.FQ, fromUntilCondition);
    }

    // cursor
    query.set(CursorMarkParams.CURSOR_MARK_PARAM, cursor.orElse(CursorMarkParams.CURSOR_MARK_START));
    query.set(CommonParams.ROWS, String.valueOf(getPartitionSize()));
    query.set(CommonParams.SORT, "id asc");

    // do the query
    SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient();
    QueryResponse response = solrClient.query(query);
    Collection<MCROAISetResolver<String, SolrDocument>> setResolver = getSetResolver(response.getResults());
    return new MCROAISolrResult(response, d -> toHeader(d, setResolver));
}
 
Example 2
Source File: TestSuggesterResponse.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuggesterResponseTerms() throws Exception {
  getSolrClient();
  addSampleDocs();

  SolrQuery query = new SolrQuery("*:*");
  query.set(CommonParams.QT, "/suggest");
  query.set("suggest.dictionary", "mySuggester");
  query.set("suggest.q", "Com");
  query.set("suggest.build", true);
  QueryRequest request = new QueryRequest(query);
  QueryResponse queryResponse = request.process(client);
  SuggesterResponse response = queryResponse.getSuggesterResponse();
  Map<String, List<String>> dictionary2suggestions = response.getSuggestedTerms();
  assertTrue(dictionary2suggestions.keySet().contains("mySuggester"));

  List<String> mySuggester = dictionary2suggestions.get("mySuggester");
  assertEquals("Computational framework", mySuggester.get(0));
  assertEquals("Computer", mySuggester.get(1));
}
 
Example 3
Source File: DistributedDebugComponentTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testTolerantSearch() throws SolrServerException, IOException {
  String badShard = DEAD_HOST_1;
  SolrQuery query = new SolrQuery();
  query.setQuery("*:*");
  query.set("debug",  "true");
  query.set("distrib", "true");
  query.setFields("id", "text");
  query.set("shards", shard1 + "," + shard2 + "," + badShard);

  // verify that the request would fail if shards.tolerant=false
  ignoreException("Server refused connection");
  expectThrows(SolrException.class, () -> collection1.query(query));

  query.set(ShardParams.SHARDS_TOLERANT, "true");
  QueryResponse response = collection1.query(query);
  assertTrue((Boolean)response.getResponseHeader().get(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY));
  @SuppressWarnings("unchecked")
  NamedList<String> badShardTrack =
          (((NamedList<NamedList<NamedList<String>>>)response.getDebugMap().get("track")).get("EXECUTE_QUERY")).get(badShard);
  assertEquals("Unexpected response size for shard", 1, badShardTrack.size());
  Entry<String, String> exception = badShardTrack.iterator().next();
  assertEquals("Expected key 'Exception' not found", "Exception", exception.getKey());
  assertNotNull("Exception message should not be null", exception.getValue());
  unIgnoreException("Server refused connection");
}
 
Example 4
Source File: SolrComponent.java    From metron with Apache License 2.0 6 votes vote down vote up
public List<Map<String, Object>> getAllIndexedDocs(String collection) {
  List<Map<String, Object>> docs = new ArrayList<>();
  CloudSolrClient solr = miniSolrCloudCluster.getSolrClient();
  solr.setDefaultCollection(collection);
  SolrQuery parameters = new SolrQuery();

  // If it's metaalert, we need to adjust the query. We want child docs with the parent,
  // not separate.
  if (collection.equals("metaalert")) {
    parameters.setQuery("source.type:metaalert")
        .setFields("*", "[child parentFilter=source.type:metaalert limit=999]");
  } else {
    parameters.set("q", "*:*");
  }
  try {
    solr.commit();
    QueryResponse response = solr.query(parameters);
    for (SolrDocument solrDocument : response.getResults()) {
      // Use the utils to make sure we get child docs.
      docs.add(SolrUtilities.toDocument(solrDocument).getDocument());
    }
  } catch (SolrServerException | IOException e) {
    e.printStackTrace();
  }
  return docs;
}
 
Example 5
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 6
Source File: ClusteringTest.java    From solr-spatial-clustering with Apache License 2.0 6 votes vote down vote up
@Test
public void belowMinSize() throws Exception {
    SolrQuery query = new SolrQuery("*:*");
    query.setRows(ROWS);
    query.set(PARAMETER_SPATIALCLUSTERING, true);
    query.set(PARAMETER_SIZE, 0);

    try {
        infrastructureRule.getSolrClient().query(query);
    } catch (SolrServerException e) {
        Throwable rootCause = e.getRootCause();

        assertTrue(rootCause instanceof IllegalArgumentException);
        assertEquals("The requested size must be at least 1.", rootCause.getMessage());
    }
}
 
Example 7
Source File: SolrConnector.java    From TagRec with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "deprecation" })
public Map<String, Double> getTopHashtagsForTweetID(String tweetID, int limit) {	
	Map<String, Double> hashtagMap = new LinkedHashMap<String, Double>();
	if (tweetID == null || tweetID.isEmpty()) {
		return hashtagMap;
	}
	
	SolrQuery solrParams = new SolrQuery();
	// query version
	//solrParams.set("q", "text:" + cleanedTweetText);
	// mlt version
	solrParams.setQueryType("/mlt");
	solrParams.set("q", "id:" + tweetID);
	solrParams.set("mlt.fl", "text");
	// additional parameters
	solrParams.set("fl", "hashtags,score");
	solrParams.set("mlt.count", 50);
	solrParams.set("rows", 50);
	QueryResponse r = null;
	try {
		r = this.server.query(solrParams);
		SolrDocumentList docs = r.getResults();
		for (SolrDocument d : docs) {
			processSolrDocument(d, hashtagMap, limit);
		}
	} catch (Exception e) {
		System.out.println("Exception with tweet-id: " + tweetID);
		e.printStackTrace();
	}
	
	return hashtagMap;
}
 
Example 8
Source File: SegmentTerminateEarlyTestState.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
void queryTimestampAscendingSegmentTerminateEarlyYes(CloudSolrClient cloudSolrClient) throws Exception {
  TestSegmentSorting.assertFalse(minTimestampDocKeys.isEmpty());
  TestSegmentSorting.assertTrue("numDocs="+numDocs+" is not even", (numDocs%2)==0);
  final Long oddFieldValue = (long) (minTimestampDocKeys.iterator().next().intValue() % 2);
  final SolrQuery query = new SolrQuery(ODD_FIELD +":"+oddFieldValue);
  query.setSort(TIMESTAMP_FIELD, SolrQuery.ORDER.asc); // a sort order that is _not_ compatible with the merge sort order
  query.setFields(KEY_FIELD, ODD_FIELD, TIMESTAMP_FIELD);
  query.setRows(1);
  query.set(CommonParams.SEGMENT_TERMINATE_EARLY, true);
  final QueryResponse rsp = cloudSolrClient.query(query);
  // check correctness of the results count
  TestSegmentSorting.assertEquals("numFound", numDocs/2, rsp.getResults().getNumFound());
  // check correctness of the first result
  if (rsp.getResults().getNumFound() > 0) {
    final SolrDocument solrDocument0 = rsp.getResults().get(0);
    final Integer idAsInt = Integer.parseInt(solrDocument0.getFieldValue(KEY_FIELD).toString());
    TestSegmentSorting.assertTrue
      (KEY_FIELD +"="+idAsInt+" of ("+solrDocument0+") is not in minTimestampDocKeys("+minTimestampDocKeys+")",
       minTimestampDocKeys.contains(idAsInt));
    TestSegmentSorting.assertEquals(ODD_FIELD, oddFieldValue, solrDocument0.getFieldValue(ODD_FIELD));
  }
  // check segmentTerminatedEarly flag
  TestSegmentSorting.assertNotNull("responseHeader.segmentTerminatedEarly missing in "+rsp.getResponseHeader(),
      rsp.getResponseHeader().get(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY));
  // segmentTerminateEarly cannot be used with incompatible sort orders
  TestSegmentSorting.assertTrue("responseHeader.segmentTerminatedEarly missing/true in "+rsp.getResponseHeader(),
      Boolean.FALSE.equals(rsp.getResponseHeader().get(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY)));
}
 
Example 9
Source File: DistributedDebugComponentTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
// commented out on: 24-Dec-2018   @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Sep-2018
public void testCompareWithNonDistributedRequest() throws SolrServerException, IOException {
  SolrQuery query = new SolrQuery();
  query.setQuery("id:1 OR id:2");
  query.setFilterQueries("id:[0 TO 10]", "id:[0 TO 5]");
  query.setRows(1);
  query.setSort("id", SolrQuery.ORDER.asc); // thus only return id:1 since rows 1
  query.set("debug",  "true");
  query.set("distrib", "true");
  query.setFields("id");
  if (random().nextBoolean()) { // can affect rb.onePassDistributedQuery
    query.addField("text");
  }
  query.set(ShardParams.DISTRIB_SINGLE_PASS, random().nextBoolean());
  query.set("shards", shard1 + "," + shard2);
  QueryResponse distribResponse = collection1.query(query);
  
  // same query but not distributed
  query.set("distrib", "false");
  query.remove("shards");
  QueryResponse nonDistribResponse = collection1.query(query);
  
  assertNotNull(distribResponse.getDebugMap().get("track"));
  assertNull(nonDistribResponse.getDebugMap().get("track"));
  assertEquals(distribResponse.getDebugMap().size() - 1, nonDistribResponse.getDebugMap().size());
  
  assertSectionEquals(distribResponse, nonDistribResponse, "explain");
  assertSectionEquals(distribResponse, nonDistribResponse, "rawquerystring");
  assertSectionEquals(distribResponse, nonDistribResponse, "querystring");
  assertSectionEquals(distribResponse, nonDistribResponse, "parsedquery");
  assertSectionEquals(distribResponse, nonDistribResponse, "parsedquery_toString");
  assertSectionEquals(distribResponse, nonDistribResponse, "QParser");
  assertSectionEquals(distribResponse, nonDistribResponse, "filter_queries");
  assertSectionEquals(distribResponse, nonDistribResponse, "parsed_filter_queries");
  
  // timing should have the same sections:
  assertSameKeys((NamedList<?>)nonDistribResponse.getDebugMap().get("timing"), (NamedList<?>)distribResponse.getDebugMap().get("timing"));
}
 
Example 10
Source File: SolrJavaLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeleteById_thenVerifyDeleted() throws SolrServerException, IOException {

    solrJavaIntegration.deleteSolrDocumentById("123456");

    SolrQuery query = new SolrQuery();
    query.set("q", "id:123456");
    QueryResponse response = solrJavaIntegration.getSolrClient().query(query);

    SolrDocumentList docList = response.getResults();
    assertEquals(0, docList.getNumFound());
}
 
Example 11
Source File: SolrJavaLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeleteByQuery_thenVerifyDeleted() throws SolrServerException, IOException {

    solrJavaIntegration.deleteSolrDocumentByQuery("name:Kenmore Dishwasher");

    SolrQuery query = new SolrQuery();
    query.set("q", "id:123456");
    QueryResponse response = null;

    response = solrJavaIntegration.getSolrClient().query(query);

    SolrDocumentList docList = response.getResults();
    assertEquals(0, docList.getNumFound());
}
 
Example 12
Source File: SolrConnector.java    From TagRec with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getTweetTextOfLastHours(String user, int hours) {
	String tweetText = "";
	SolrQuery solrParams = new SolrQuery();
	solrParams.set("q", "userid:" + user);
	solrParams.set("sort", "timestamp desc");
	solrParams.set("fl", "text,timestamp");
	solrParams.set("rows", 100);
	QueryResponse r = null;
	try {
		r = this.server.query(solrParams);
		SolrDocumentList docs = r.getResults();
		Long threshold = null;
		for (SolrDocument d : docs) {
			String timestampString = (String) d.get("timestamp");
			Long timestamp = Long.parseLong(timestampString.substring(0, timestampString.indexOf(".")));
			if (threshold == null) {
				threshold = timestamp - hours * 60 * 60;
			}
			if (timestamp > threshold.longValue()) {
				tweetText += ((String) d.get("text") + " ");
			} else {
				break;
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}		
	return tweetText;
}
 
Example 13
Source File: ItemSearchServiceLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSearchingWithIncompleteKeyword_thenKeywordSuggestionsShouldBeReturned() throws Exception {
    itemSearchService.index("hm0001", "Brand1 Washing Machine", "Home Appliances", 100f);
    itemSearchService.index("hm0002", "Brand1 Refrigerator", "Home Appliances", 300f);
    itemSearchService.index("hm0003", "Brand2 Ceiling Fan", "Home Appliances", 200f);
    itemSearchService.index("hm0004", "Brand2 Dishwasher", "Home washing equipments", 250f);

    SolrQuery query = new SolrQuery();
    query.setRequestHandler("/suggest");
    query.set("suggest", "true");
    query.set("suggest.build", "true");
    query.set("suggest.dictionary", "mySuggester");
    query.set("suggest.q", "Hom");
    QueryResponse response = solrClient.query(query);

    SuggesterResponse suggesterResponse = response.getSuggesterResponse();
    Map<String, List<String>> suggestedTerms = suggesterResponse.getSuggestedTerms();
    List<String> suggestions = suggestedTerms.get("mySuggester");

    assertEquals(2, suggestions.size());

    for (String term : suggestions) {
        if (!"Home Appliances".equals(term) && !"Home washing equipments".equals(term)) {
            fail("Unexpected suggestions");
        }
    }

}
 
Example 14
Source File: SolrSearchDaoTest.java    From metron with Apache License 2.0 5 votes vote down vote up
@Test
public void groupShouldProperlyReturnGroupResponse() throws Exception {
  GroupRequest groupRequest = mock(GroupRequest.class);
  QueryResponse queryResponse = mock(QueryResponse.class);
  GroupResponse groupResponse = mock(GroupResponse.class);

  solrSearchDao = spy(new SolrSearchDao(client, accessConfig));
  Group group1 = new Group();
  group1.setField("field1");
  Group group2 = new Group();
  group2.setField("field2");
  when(groupRequest.getQuery()).thenReturn("query");
  when(groupRequest.getGroups()).thenReturn(Arrays.asList(group1, group2));
  when(groupRequest.getScoreField()).thenReturn(Optional.of("scoreField"));
  when(groupRequest.getIndices()).thenReturn(Arrays.asList("bro", "snort"));
  when(client.query(any())).thenReturn(queryResponse);
  doReturn(groupResponse).when(solrSearchDao).buildGroupResponse(groupRequest, queryResponse);
  SolrQuery expectedSolrQuery = new SolrQuery()
      .setStart(0)
      .setRows(0)
      .setQuery("query");
  expectedSolrQuery.set("collection", "bro,snort");
  expectedSolrQuery.set("stats", true);
  expectedSolrQuery.set("stats.field", "{!tag=piv1 sum=true}scoreField");
  expectedSolrQuery.set("facet", true);
  expectedSolrQuery.set("facet.pivot", "{!stats=piv1}field1,field2");

  // Feed back an appropriate response regarding the collections
  NamedList<Object> namedList = new NamedList<>();
  namedList.add("collections", Arrays.asList("bro","snort"));
  when(client.request(any(), any())).thenReturn(namedList);

  assertEquals(groupResponse, solrSearchDao.group(groupRequest));
  verify(client).query(argThat(new SolrQueryMatcher(expectedSolrQuery)));
  verify(client).request(any(), any());
  verify(solrSearchDao).buildGroupResponse(groupRequest, queryResponse);

  verifyNoMoreInteractions(client);
}
 
Example 15
Source File: TestTlogReplica.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void checkRTG(int from, int to, List<JettySolrRunner> solrRunners) throws Exception{
  for (JettySolrRunner solrRunner: solrRunners) {
    try (SolrClient client = solrRunner.newClient()) {
      for (int i = from; i <= to; i++) {
        SolrQuery query = new SolrQuery();
        query.set("distrib", false);
        query.setRequestHandler("/get");
        query.set("id",i);
        QueryResponse res = client.query(collectionName, query);
        assertNotNull("Can not find doc "+ i + " in " + solrRunner.getBaseUrl(),res.getResponse().get("doc"));
      }
    }
  }
}
 
Example 16
Source File: MavenCentralSearchApiServiceImpl.java    From artifact-listener with Apache License 2.0 5 votes vote down vote up
private List<ArtifactVersionBean> getArtifactVersions(String groupId, String artifactId, int offset, int maxRows) throws ServiceException {
	if (!StringUtils.hasText(groupId) || ! StringUtils.hasText(artifactId)) {
		return Lists.newArrayListWithCapacity(0);
	}
	
	BooleanQuery bq = new BooleanQuery();
	bq.add(new TermQuery(new Term(MavenCentralSearchApiConstants.GROUP_FIELD, groupId)), Occur.MUST);
	bq.add(new TermQuery(new Term(MavenCentralSearchApiConstants.ARTIFACT_FIELD, artifactId)), Occur.MUST);
	
	SolrQuery solrQuery = new SolrQuery(LuceneUtils.queryToString(bq));
	solrQuery.set(CoreAdminParams.CORE, MavenCentralSearchApiConstants.CORE_GAV);

	QueryResponse response = query(solrQuery, offset, maxRows);
	return response.getBeans(ArtifactVersionBean.class);
}
 
Example 17
Source File: SolrUtil.java    From ambari-logsearch with Apache License 2.0 4 votes vote down vote up
private static void setFacetLimit(SolrQuery solrQuery, int limit) {
  solrQuery.set("facet.limit", limit);
}
 
Example 18
Source File: SegmentTerminateEarlyTestState.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
void queryTimestampDescendingSegmentTerminateEarlyNo(CloudSolrClient cloudSolrClient) throws Exception {
  TestSegmentSorting.assertFalse(maxTimestampDocKeys.isEmpty());
  TestSegmentSorting.assertTrue("numDocs="+numDocs+" is not even", (numDocs%2)==0);
  final Long oddFieldValue = (long) (maxTimestampDocKeys.iterator().next().intValue() % 2);
  final SolrQuery query = new SolrQuery(ODD_FIELD +":"+oddFieldValue);
  query.setSort(TIMESTAMP_FIELD, SolrQuery.ORDER.desc);
  query.setFields(KEY_FIELD, ODD_FIELD, TIMESTAMP_FIELD);
  query.setRows(1);
  final Boolean shardsInfoWanted = (rand.nextBoolean() ? null : rand.nextBoolean());
  if (shardsInfoWanted != null) {
    query.set(ShardParams.SHARDS_INFO, shardsInfoWanted.booleanValue());
  }
  query.set(CommonParams.SEGMENT_TERMINATE_EARLY, false);
  final QueryResponse rsp = cloudSolrClient.query(query);
  // check correctness of the results count
  TestSegmentSorting.assertEquals("numFound", numDocs/2, rsp.getResults().getNumFound());
  // check correctness of the first result
  if (rsp.getResults().getNumFound() > 0) {
    final SolrDocument solrDocument0 = rsp.getResults().get(0);
    final Integer idAsInt = Integer.parseInt(solrDocument0.getFieldValue(KEY_FIELD).toString());
    TestSegmentSorting.assertTrue
      (KEY_FIELD +"="+idAsInt+" of ("+solrDocument0+") is not in maxTimestampDocKeys("+maxTimestampDocKeys+")",
       maxTimestampDocKeys.contains(idAsInt));
    TestSegmentSorting.assertEquals(ODD_FIELD, oddFieldValue, rsp.getResults().get(0).getFieldValue(ODD_FIELD));
  }
  // check segmentTerminatedEarly flag
  TestSegmentSorting.assertNull("responseHeader.segmentTerminatedEarly present in "+rsp.getResponseHeader(),
      rsp.getResponseHeader().get(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY));
  TestSegmentSorting.assertFalse("responseHeader.segmentTerminatedEarly present/true in "+rsp.getResponseHeader(),
      Boolean.TRUE.equals(rsp.getResponseHeader().get(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY)));
  // check shards info
  final Object shardsInfo = rsp.getResponse().get(ShardParams.SHARDS_INFO);
  if (!Boolean.TRUE.equals(shardsInfoWanted)) {
    TestSegmentSorting.assertNull(ShardParams.SHARDS_INFO, shardsInfo);
  } else {
    TestSegmentSorting.assertNotNull(ShardParams.SHARDS_INFO, shardsInfo);
    int segmentTerminatedEarlyShardsCount = 0;
    for (Map.Entry<String, ?> si : (SimpleOrderedMap<?>)shardsInfo) {
      if (Boolean.TRUE.equals(((SimpleOrderedMap)si.getValue()).get(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY))) {
        segmentTerminatedEarlyShardsCount += 1;
      }
    }
    TestSegmentSorting.assertEquals("shards reporting "+SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY,
        0, segmentTerminatedEarlyShardsCount);
  }
}
 
Example 19
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 20
Source File: SolrMetaAlertSearchDao.java    From metron with Apache License 2.0 4 votes vote down vote up
@Override
public SearchResponse getAllMetaAlertsForAlert(String guid) throws InvalidSearchException {
  if (guid == null || guid.trim().isEmpty()) {
    throw new InvalidSearchException("Guid cannot be empty");
  }

  // Searches for all alerts containing the meta alert guid in it's "metalerts" array
  // The query has to match the parentFilter to avoid errors.  Guid must also be explicitly
  // included.
  String activeClause =
      MetaAlertConstants.STATUS_FIELD + ":" + MetaAlertStatus.ACTIVE.getStatusString();
  String guidClause = Constants.GUID + ":" + guid;
  String fullClause = "{!parent which=" + activeClause + "}" + guidClause;
  String metaalertTypeClause = config.getSourceTypeField() + ":" + MetaAlertConstants.METAALERT_TYPE;
  SolrQuery solrQuery = new SolrQuery()
      .setQuery(fullClause)
      .setFields("*", "[child parentFilter=" + metaalertTypeClause + " limit=999]")
      .addSort(Constants.GUID,
          SolrQuery.ORDER.asc); // Just do basic sorting to track where we are

  // Use Solr's Cursors to handle the paging, rather than doing it manually.
  List<SearchResult> allResults = new ArrayList<>();
  try {
    String cursorMark = CursorMarkParams.CURSOR_MARK_START;
    boolean done = false;
    while (!done) {
      solrQuery.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark);
      QueryResponse rsp = solrClient.query(METAALERTS_COLLECTION, solrQuery);
      String nextCursorMark = rsp.getNextCursorMark();
      rsp.getResults().stream()
          .map(solrDocument -> SolrUtilities.getSearchResult(solrDocument, null,
                  solrSearchDao.getAccessConfig().getIndexSupplier()))
          .forEachOrdered(allResults::add);
      if (cursorMark.equals(nextCursorMark)) {
        done = true;
      }
      cursorMark = nextCursorMark;
    }
  } catch (IOException | SolrServerException e) {
    throw new InvalidSearchException("Unable to complete search", e);
  }

  SearchResponse searchResponse = new SearchResponse();
  searchResponse.setResults(allResults);
  searchResponse.setTotal(allResults.size());
  return searchResponse;
}