Java Code Examples for org.apache.solr.client.solrj.response.QueryResponse#getResponse()

The following examples show how to use org.apache.solr.client.solrj.response.QueryResponse#getResponse() . 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: AlfrescoSolrSortIT.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void AlfrescoMLCollatableFieldType_emptyValuesSortingDesc_shouldRankThemLast() throws Exception
{
    prepareIndexSegmentWithAllNonNullFieldValues("mltext@m__sort@{http://www.alfresco.org/model/content/1.0}title");

    putHandleDefaults();
    // Docs with id 1, 3, 5 and 6 should be last (note that these will be sorted by indexing time).
    String[] expectedRanking = new String[]{"2","4","1","3","5","6"};

    QueryResponse response = query(getDefaultTestClient(), true,
            "{\"query\":\"(id:(1 2 3 4 5 6))\",\"locales\":[\"en\"], \"templates\": [{\"name\":\"t1\", \"template\":\"%cm:content\"}], \"authorities\": [\"joel\"], \"tenants\": []}",
            params("qt", "/afts", "shards.qt", "/afts", "start", "0", "rows", "100", "sort", "mltext@m__sort@{http://www.alfresco.org/model/content/1.0}title desc"));

    NamedList<?> res = response.getResponse();
    SolrDocumentList searchResults = (SolrDocumentList)res.get("response");
    for(int i=0;i<searchResults.size();i++)
    {
        assertThat(searchResults.get(i).get("id"),is(expectedRanking[i]));
    }
}
 
Example 2
Source File: DistributedAlfrescoSolrSpellcheckerIT.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testSpellcheckerOutputFormat() throws Exception
{
    putHandleDefaults();
    QueryResponse response = query(getDefaultTestClient(), true,
            "{\"query\":\"(YYYYY BBBBB AND (id:(1 2 3 4 5 6)))\",\"locales\":[\"en\"], \"templates\": [{\"name\":\"t1\", \"template\":\"%cm:content\"}], \"authorities\": [\"joel\"], \"tenants\": []}",
            params("spellcheck.q", "YYYYY BBBBB", "qt", "/afts", "shards.qt", "/afts", "start", "0", "rows", "100", "spellcheck", "true"));

    NamedList res = response.getResponse();
    NamedList spellcheck = (NamedList)res.get("spellcheck");
    NamedList suggestions = (NamedList)spellcheck.get("suggestions"); // Solr 4 format
    NamedList collation = (NamedList)suggestions.getVal(2); // The third suggestion should be collation in the Solr format.
    String collationQuery = (String)collation.get("collationQuery");
    String collationQueryString = (String)collation.get("collationQueryString");
    int hits = (int)collation.get("hits");
    assertTrue(hits == 3);
    assertTrue(collationQuery.equals("(yyyyyyy bbbbbbb AND (id:(1 2 3 4 5 6)))"));
    assertTrue(collationQueryString.equals("yyyyyyy bbbbbbb"));
}
 
Example 3
Source File: AlfrescoSolrSortIT.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void AlfrescoCollatableFieldType_emptyValuesSortingAsc__shouldBeRankedFirst() throws Exception
{
    prepareIndexSegmentWithAllNonNullFieldValues("text@s__sort@{http://www.alfresco.org/model/content/1.0}title");
    putHandleDefaults();
    // Docs with id 1, 3, 5 and 6 should be first (note that these will be sorted by indexing time).
    String[] expectedRanking = new String[]{"1","3","5","6","4","2"};
    
    QueryResponse response = query(getDefaultTestClient(), true,
            "{\"query\":\"(id:(1 2 3 4 5 6))\",\"locales\":[\"en\"], \"templates\": [{\"name\":\"t1\", \"template\":\"%cm:content\"}], \"authorities\": [\"joel\"], \"tenants\": []}",
            params("qt", "/afts", "shards.qt", "/afts", "start", "0", "rows", "100", "sort", "text@s__sort@{http://www.alfresco.org/model/content/1.0}title asc"));

    NamedList<?> res = response.getResponse();
    SolrDocumentList searchResults = (SolrDocumentList)res.get("response");
    for(int i=0;i<searchResults.size();i++){
        assertThat(searchResults.get(i).get("id"),is(expectedRanking[i]));
    }
}
 
Example 4
Source File: SignificantTermsStream.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
public NamedList<Double> call() throws Exception {
  ModifiableSolrParams params = new ModifiableSolrParams();
  HttpSolrClient solrClient = cache.getHttpSolrClient(baseUrl);

  params.add(DISTRIB, "false");
  params.add("fq","{!significantTerms}");

  for(Map.Entry<String, String> entry : paramsMap.entrySet()) {
    params.add(entry.getKey(), entry.getValue());
  }

  params.add("minDocFreq", Float.toString(minDocFreq));
  params.add("maxDocFreq", Float.toString(maxDocFreq));
  params.add("minTermLength", Integer.toString(minTermLength));
  params.add("field", field);
  params.add("numTerms", String.valueOf(numTerms*5));
  if (streamContext.isLocal()) {
    params.add("distrib", "false");
  }

  QueryRequest request= new QueryRequest(params, SolrRequest.METHOD.POST);
  QueryResponse response = request.process(solrClient);
  NamedList res = response.getResponse();
  return res;
}
 
Example 5
Source File: FeaturesSelectionStream.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked"})
public NamedList<Double> call() throws Exception {
  ModifiableSolrParams params = new ModifiableSolrParams();
  HttpSolrClient solrClient = cache.getHttpSolrClient(baseUrl);

  params.add(DISTRIB, "false");
  params.add("fq","{!igain}");

  for(Map.Entry<String, String> entry : paramsMap.entrySet()) {
    params.add(entry.getKey(), entry.getValue());
  }

  params.add("outcome", outcome);
  params.add("positiveLabel", Integer.toString(positiveLabel));
  params.add("field", field);
  params.add("numTerms", String.valueOf(numTerms));

  QueryRequest request= new QueryRequest(params);
  QueryResponse response = request.process(solrClient);
  NamedList res = response.getResponse();
  return res;
}
 
Example 6
Source File: LegacyAbstractAnalyticsCloudTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected NamedList<Object> queryLegacyCloudAnalytics(String[] testParams) throws SolrServerException, IOException, InterruptedException, TimeoutException {
  ModifiableSolrParams params = new ModifiableSolrParams();
  params.set("q", "*:*");
  params.set("indent", "true");
  params.set("olap", "true");
  params.set("rows", "0");
  for (int i = 0; i + 1 < testParams.length;) {
    params.add(testParams[i++], testParams[i++]);
  }
  cluster.waitForAllNodes(10000);
  QueryRequest qreq = new QueryRequest(params);
  QueryResponse resp = qreq.process(cluster.getSolrClient(), COLLECTIONORALIAS);
  final NamedList<Object> response = resp.getResponse();
  assertRequestTimeout(params);
  return response;
}
 
Example 7
Source File: TestRandomFlRTGCloud.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/** 
 * trivial helper method to deal with diff response structure between using a single 'id' param vs
 * 2 or more 'id' params (or 1 or more 'ids' params).
 *
 * @return List from response, or a synthetic one created from single response doc if 
 * <code>expectList</code> was false; May be empty; May be null if response included null list.
 */
private static SolrDocumentList getDocsFromRTGResponse(final boolean expectList, final QueryResponse rsp) {
  if (expectList) {
    return rsp.getResults();
  }
  
  // else: expect single doc, make our own list...
  
  final SolrDocumentList result = new SolrDocumentList();
  NamedList<Object> raw = rsp.getResponse();
  Object doc = raw.get("doc");
  if (null != doc) {
    result.add((SolrDocument) doc);
    result.setNumFound(1);
  }
  return result;
}
 
Example 8
Source File: CdcrTestsUtil.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected static Object getFingerPrintMaxVersion(CloudSolrClient client, String shardNames, int numDocs) throws SolrServerException, IOException, InterruptedException {
  ModifiableSolrParams params = new ModifiableSolrParams();
  params.set(CommonParams.QT, "/get");
  params.set("fingerprint", true);
  params.set("shards", shardNames);
  params.set("getVersions", numDocs);

  QueryResponse response = null;
  long start = System.nanoTime();
  while (System.nanoTime() - start <= TimeUnit.NANOSECONDS.convert(20, TimeUnit.SECONDS)) {
    response = client.query(params);
    if (response.getResponse() != null && response.getResponse().get("fingerprint") != null) {
      return (long) ((LinkedHashMap) response.getResponse().get("fingerprint")).get("maxVersionEncountered");
    }
    Thread.sleep(200);
  }
  log.error("maxVersionEncountered not found for client : {} in 20 attempts", client);
  return null;
}
 
Example 9
Source File: TestCloudJSONFacetSKGEquiv.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * returns the <b>FIRST</b> NamedList (under the implicit 'null' FacetQuery) in the "facet-trace" output 
 * of the request.  Should not be used with multiple "top level" facets 
 * (the output is too confusing in cloud mode to be confident where/qhy each NamedList comes from)
 */
private NamedList<Object> getFacetDebug(final SolrParams params) {
  try {
    final QueryResponse rsp = (new QueryRequest(params)).process(getRandClient(random()));
    assertNotNull(params + " is null rsp?", rsp);
    @SuppressWarnings({"rawtypes"})
    final NamedList topNamedList = rsp.getResponse();
    assertNotNull(params + " is null topNamedList?", topNamedList);
    
    // skip past the (implicit) top Facet query to get it's "sub-facets" (the real facets)...
    @SuppressWarnings({"unchecked"})
    final List<NamedList<Object>> facetDebug =
      (List<NamedList<Object>>) topNamedList.findRecursive("debug", "facet-trace", "sub-facet");
    assertNotNull(topNamedList + " ... null facet debug?", facetDebug);
    assertFalse(topNamedList + " ... not even one facet debug?", facetDebug.isEmpty());
    return facetDebug.get(0);
  } catch (Exception e) {
    throw new RuntimeException("query failed: " + params + ": " + 
                               e.getMessage(), e);
  } 

}
 
Example 10
Source File: TestCloudJSONFacetSKGEquiv.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**     
 * We ignore {@link QueryResponse#getJsonFacetingResponse()} because it isn't as useful for
 * doing a "deep equals" comparison across requests
 */
@SuppressWarnings({"rawtypes"})
private NamedList getFacetResponse(final SolrParams params) {
  try {
    final QueryResponse rsp = (new QueryRequest(params)).process(getRandClient(random()));
    assertNotNull(params + " is null rsp?", rsp);
    final NamedList topNamedList = rsp.getResponse();
    assertNotNull(params + " is null topNamedList?", topNamedList);
    final NamedList facetResponse = (NamedList) topNamedList.get("facets");
    assertNotNull("null facet results?", facetResponse);
    assertEquals("numFound mismatch with top count?",
                 rsp.getResults().getNumFound(), ((Number)facetResponse.get("count")).longValue());
    
    return facetResponse;
    
  } catch (Exception e) {
    throw new RuntimeException("query failed: " + params + ": " + 
                               e.getMessage(), e);
  }
}
 
Example 11
Source File: SolrDocumentSearch.java    From BioSolr with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private List<Object> findFacetTree(QueryResponse response, String field) {
	NamedList<Object> baseResponse = response.getResponse();
	NamedList<Object> facetTrees = (NamedList<Object>) baseResponse.findRecursive("facet_counts", "facet_trees");
	
	return facetTrees == null ? null : facetTrees.getAll(field);
}
 
Example 12
Source File: DistributedSuggestComponentTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void validateControlData(QueryResponse control) throws Exception
{    
  NamedList<Object> nl = control.getResponse();
  @SuppressWarnings("unchecked")
  Map<String, SimpleOrderedMap<NamedList<Object>>> sc = (Map<String, SimpleOrderedMap<NamedList<Object>>>) nl.get("suggest");
  String command = (String) nl.get("command");
  if(sc.size() == 0 && command == null) {
    Assert.fail("Control data did not return any suggestions or execute any command");
  }
}
 
Example 13
Source File: DistributedSpellCheckComponentTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void validateControlData(QueryResponse control) throws Exception
{    
  NamedList<Object> nl = control.getResponse();
  @SuppressWarnings("unchecked")
  NamedList<Object> sc = (NamedList<Object>) nl.get("spellcheck");
  @SuppressWarnings("unchecked")
  NamedList<Object> sug = (NamedList<Object>) sc.get("suggestions");
  if(sug.size()==0) {
    Assert.fail("Control data did not return any suggestions.");
  }
}
 
Example 14
Source File: TestReplicationHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testFetchIndexShouldReportErrorsWhenTheyOccur() throws Exception  {
  int masterPort = masterJetty.getLocalPort();
  masterJetty.stop();
  SolrQuery q = new SolrQuery();
  q.add("qt", "/replication")
      .add("wt", "json")
      .add("wait", "true")
      .add("command", "fetchindex")
      .add("masterUrl", buildUrl(masterPort));
  QueryResponse response = slaveClient.query(q);
  NamedList<Object> resp = response.getResponse();
  assertNotNull(resp);
  assertEquals("Fetch index with wait=true should have returned an error response", "ERROR", resp.get("status"));
}
 
Example 15
Source File: TestReplicationHandler.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testFileListShouldReportErrorsWhenTheyOccur() throws Exception {
  SolrQuery q = new SolrQuery();
  q.add("qt", "/replication")
      .add("wt", "json")
      .add("command", "filelist")
      .add("generation", "-2"); // A 'generation' value not matching any commit point should cause error.
  QueryResponse response = slaveClient.query(q);
  NamedList<Object> resp = response.getResponse();
  assertNotNull(resp);
  assertEquals("ERROR", resp.get("status"));
  assertEquals("invalid index generation", resp.get("message"));
}
 
Example 16
Source File: AnalyticsMergeStrategyTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void assertCount(QueryResponse rsp, int count) throws Exception {
  @SuppressWarnings({"rawtypes"})
  NamedList response = rsp.getResponse();
  @SuppressWarnings({"rawtypes"})
  NamedList analytics = (NamedList)response.get("analytics");
  Integer c = (Integer)analytics.get("mycount");
  if(c.intValue() != count) {
    throw new Exception("Count is not correct:"+count+":"+c.intValue());
  }

  long numFound = rsp.getResults().getNumFound();
  if(c.intValue() != numFound) {
    throw new Exception("Count does not equal numFound:"+c.intValue()+":"+numFound);
  }
}
 
Example 17
Source File: AnalyticsMergeStrategyTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void assertCountOnly(QueryResponse rsp, int count) throws Exception {
  @SuppressWarnings({"rawtypes"})
  NamedList response = rsp.getResponse();
  @SuppressWarnings({"rawtypes"})
  NamedList analytics = (NamedList)response.get("analytics");
  Integer c = (Integer)analytics.get("mycount");
  if(c.intValue() != count) {
    throw new Exception("Count is not correct:"+count+":"+c.intValue());
  }
}
 
Example 18
Source File: PeerSyncWithLeader.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private NamedList<Object> request(ModifiableSolrParams params, String onFail) {
  try {
    QueryResponse rsp = new QueryRequest(params, SolrRequest.METHOD.POST).process(clientToLeader);
    Exception exception = rsp.getException();
    if (exception != null) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, onFail);
    }
    return rsp.getResponse();
  } catch (SolrServerException | IOException e) {
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, onFail);
  }
}
 
Example 19
Source File: TextLogitStream.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public Tuple call() throws Exception {
  ModifiableSolrParams params = new ModifiableSolrParams();
  HttpSolrClient solrClient = cache.getHttpSolrClient(baseUrl);

  params.add(DISTRIB, "false");
  params.add("fq","{!tlogit}");
  params.add("feature", feature);
  params.add("terms", TextLogitStream.toString(terms));
  params.add("idfs", TextLogitStream.toString(idfs));

  for(Entry<String, String> entry : paramsMap.entrySet()) {
    params.add(entry.getKey(), entry.getValue());
  }

  if(weights != null) {
    params.add("weights", TextLogitStream.toString(weights));
  }

  params.add("iteration", Integer.toString(iteration));
  params.add("outcome", outcome);
  params.add("positiveLabel", Integer.toString(positiveLabel));
  params.add("threshold", Double.toString(threshold));
  params.add("alpha", Double.toString(learningRate));

  QueryRequest  request= new QueryRequest(params, SolrRequest.METHOD.POST);
  QueryResponse response = request.process(solrClient);
  @SuppressWarnings({"rawtypes"})
  NamedList res = response.getResponse();

  @SuppressWarnings({"rawtypes"})
  NamedList logit = (NamedList)res.get("logit");

  @SuppressWarnings({"unchecked"})
  List<Double> shardWeights = (List<Double>)logit.get("weights");
  double shardError = (double)logit.get("error");

  Tuple tuple = new Tuple();

  tuple.put("error", shardError);
  tuple.put("weights", shardWeights);
  tuple.put("evaluation", logit.get("evaluation"));

  return tuple;
}