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

The following examples show how to use org.apache.solr.client.solrj.SolrQuery#setSort() . 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: CollectionManagementService.java    From vind with Apache License 2.0 6 votes vote down vote up
public Long getVersionAndInstallIfNecessary(String dependency) {

        try (CloudSolrClient client = createCloudSolrClient()) {
            SolrQuery query = new SolrQuery("blobName:"+Utils.toBlobName(dependency));
            query.setSort("version", SolrQuery.ORDER.desc);
            QueryResponse response = client.query(".system",query);

            if(response.getResults().getNumFound() > 0) { //should could look for updates here as well?

                return Long.valueOf(response.getResults().get(0).get("version").toString());
            } else {
                Path configDirectory = Files.createTempDirectory(Utils.normalizeFileName(dependency));

                Path jarFile = Utils.downloadToTempDir(configDirectory, repositories, dependency);
                return uploadRuntimeLib(dependency, jarFile);
            }

        } catch (SolrServerException | IOException e) {
            logger.warn("Cannot load runtime dependeny " + dependency + ". This may cause runtime issues.");
            return -1L;
        }
    }
 
Example 2
Source File: UsingSolrJRefGuideExamplesTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void queryBeanValueTypeExample() throws Exception {
  expectLine("Found 3 documents");
  expectLine("id: 1; name: Fitbit Alta");
  expectLine("id: 2; name: Sony Walkman");
  expectLine("id: 3; name: Garmin GPS");
  
  // tag::solrj-query-bean-value-type[]
  final SolrClient client = getSolrClient();

  final SolrQuery query = new SolrQuery("*:*");
  query.addField("id");
  query.addField("name");
  query.setSort("id", ORDER.asc);

  final QueryResponse response = client.query("techproducts", query);
  final List<TechProduct> products = response.getBeans(TechProduct.class);
  // end::solrj-query-bean-value-type[]

  print("Found " + products.size() + " documents");
  for (TechProduct product : products) {
    print("id: " + product.id + "; name: " + product.name);
  }
}
 
Example 3
Source File: SegmentTerminateEarlyTestState.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
void queryTimestampDescending(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);
  // CommonParams.SEGMENT_TERMINATE_EARLY parameter intentionally absent
  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, solrDocument0.getFieldValue(ODD_FIELD));
  }
  // check segmentTerminatedEarly flag
  TestSegmentSorting.assertNull("responseHeader.segmentTerminatedEarly present in "+rsp.getResponseHeader(),
      rsp.getResponseHeader().get(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY));
}
 
Example 4
Source File: DocValuesNotIndexedTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void checkSortOrder(CloudSolrClient client, List<FieldProps> props, String sortDir, String[] order, String[] orderBool) throws IOException, SolrServerException {
  for (FieldProps prop : props) {
    final SolrQuery solrQuery = new SolrQuery("q", "*:*", "rows", "100");
    solrQuery.setSort(prop.getName(), "asc".equals(sortDir) ? SolrQuery.ORDER.asc : SolrQuery.ORDER.desc);
    solrQuery.addSort("id", SolrQuery.ORDER.asc);
    final QueryResponse rsp = client.query(COLLECTION, solrQuery);
    SolrDocumentList res = rsp.getResults();
    assertEquals("Should have exactly " + order.length + " documents returned", order.length, res.getNumFound());
    String expected;
    for (int idx = 0; idx < res.size(); ++idx) {
      if (prop.getName().startsWith("bool")) expected = orderBool[idx];
      else expected = order[idx];
      assertEquals("Documents in wrong order for field: " + prop.getName(),
          expected, res.get(idx).get("id"));
    }
  }
}
 
Example 5
Source File: ServiceLogsManager.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
private SolrServiceLogData getNextHitForKeyword(ServiceLogRequest request, String keyword, boolean isNext, String event, boolean timeAscending, String nextOrPreviousPageDate) {
  if (hasNextOrAscOrder(isNext, timeAscending)) {
    request.setTo(nextOrPreviousPageDate);
  } else {
    request.setFrom(nextOrPreviousPageDate);
  }
  SimpleQuery keywordNextQuery = conversionService.convert(request, SimpleQuery.class);
  keywordNextQuery.addFilterQuery(new SimpleFilterQuery(new Criteria(KEY_LOG_MESSAGE).contains(keyword)));
  keywordNextQuery.setRows(1);
  SolrQuery kewordNextSolrQuery = new DefaultQueryParser().doConstructSolrQuery(keywordNextQuery);
  kewordNextSolrQuery.setStart(0);
  if (hasNextOrAscOrder(isNext, timeAscending)) {
    kewordNextSolrQuery.setSort(LOGTIME, SolrQuery.ORDER.desc);
  } else {
    kewordNextSolrQuery.setSort(LOGTIME, SolrQuery.ORDER.asc);
  }
  kewordNextSolrQuery.addSort(SEQUENCE_ID, SolrQuery.ORDER.desc);
  QueryResponse queryResponse = serviceLogsSolrDao.process(kewordNextSolrQuery, event);
  if (queryResponse == null) {
    throw new NotFoundException(String.format("The keyword \"%s\" was not found", keyword));
  }
  List<SolrServiceLogData> solrServiceLogDataList = queryResponse.getBeans(SolrServiceLogData.class);
  if (!CollectionUtils.isNotEmpty(solrServiceLogDataList)) {
    throw new NotFoundException(String.format("The keyword \"%s\" was not found", keyword));
  }
  return solrServiceLogDataList.get(0);
}
 
Example 6
Source File: StandardSearchEngine.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Prepares the query for a search.
 */
protected SolrQuery prepareSearchQuery(String expression, String[] filters, String expressionLanguage,
		Integer rows) {
	SolrQuery query = new SolrQuery();
	query.setQuery(expression);
	query.setSort(SortClause.desc("score"));
	if (rows != null)
		query.setRows(rows);
	if (filters != null)
		query.addFilterQuery(filters);

	query.set("exprLang", expressionLanguage);
	return query;
}
 
Example 7
Source File: SolrReader.java    From hive-solr with MIT License 5 votes vote down vote up
/***
 * 初始化SolrQuery
 * @param sq  SolrQuery
 * @param cursorMark 游标
 */
public void init(SolrQuery sq,String cursorMark){
    sq.setSort(solr_pk, SolrQuery.ORDER.asc);
    sq.set("cursorMark", cursorMark);
    sq.set("q",solr_query);
    sq.setRows(solrBatchSize);
}
 
Example 8
Source File: UsingSolrJRefGuideExamplesTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void queryWithSolrQueryExample() throws Exception {
  final int numResultsToReturn = 3;
  expectLine("Found 3 documents");
  expectLine("id: 1; name: Fitbit Alta");
  expectLine("id: 2; name: Sony Walkman");
  expectLine("id: 3; name: Garmin GPS");
  final SolrClient client = getSolrClient();

  // tag::solrj-query-with-solrquery[]
  final SolrQuery query = new SolrQuery("*:*");
  query.addField("id");
  query.addField("name");
  query.setSort("id", ORDER.asc);
  query.setRows(numResultsToReturn);
  // end::solrj-query-with-solrquery[]

  final QueryResponse response = client.query("techproducts", query);
  final SolrDocumentList documents = response.getResults();

  print("Found " + documents.getNumFound() + " documents");
  assertEquals(numResultsToReturn, documents.size());
  for(SolrDocument document : documents) {
    final String id = (String) document.getFirstValue("id");
    final String name = (String) document.getFirstValue("name");
    
    print("id: "+ id + "; name: " + name);
  }
}
 
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: SegmentTerminateEarlyTestState.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
void queryTimestampDescendingSegmentTerminateEarlyYesGrouped(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);
  query.set(CommonParams.SEGMENT_TERMINATE_EARLY, true);
  TestSegmentSorting.assertTrue("numDocs="+numDocs+" is not quad-able", (numDocs%4)==0);
  query.add("group.field", QUAD_FIELD);
  query.set("group", true);
  final QueryResponse rsp = cloudSolrClient.query(query);
  // check correctness of the results count
  TestSegmentSorting.assertEquals("matches", numDocs/2, rsp.getGroupResponse().getValues().get(0).getMatches());
  // check correctness of the first result
  if (rsp.getGroupResponse().getValues().get(0).getMatches() > 0) {
    final SolrDocument solrDocument = rsp.getGroupResponse().getValues().get(0).getValues().get(0).getResult().get(0);
    final Integer idAsInt = Integer.parseInt(solrDocument.getFieldValue(KEY_FIELD).toString());
    TestSegmentSorting.assertTrue
      (KEY_FIELD +"="+idAsInt+" of ("+solrDocument+") is not in maxTimestampDocKeys("+maxTimestampDocKeys+")",
       maxTimestampDocKeys.contains(idAsInt));
    TestSegmentSorting.assertEquals(ODD_FIELD, oddFieldValue, solrDocument.getFieldValue(ODD_FIELD));
  }
  // check segmentTerminatedEarly flag
  // at present segmentTerminateEarly cannot be used with grouped queries
  TestSegmentSorting.assertFalse("responseHeader.segmentTerminatedEarly present/true in "+rsp.getResponseHeader(),
      Boolean.TRUE.equals(rsp.getResponseHeader().get(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY)));
}
 
Example 11
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 12
Source File: SearchITCase.java    From apache-solr-essentials with Apache License 2.0 5 votes vote down vote up
/**
 * Selects all documents using an handler configured with SolrQueryParser
 * 
 * @throws Exception hopefully never, otherwise the test fails.
 */
@Test
public void selectAll() throws Exception {
	// 1. Prepare the Query object
	// The query string can be directly injected in the constructor
	final SolrQuery query = new SolrQuery("*:*");
	query.setRequestHandler("/h1");
	
	// These settings will override the "defaults" section
	query.setFacet(false);
	query.setHighlight(false);
	query.setSort("released", ORDER.desc);
	
	// We are asking 5 documents per page
	query.setRows(5);
	
	// 2. Send the query request and get the corresponding response.
	final QueryResponse response = SEARCHER.query(query);
	
	// 3. Get the result object, containing documents and metadata.
	final SolrDocumentList documents = response.getResults();
	
	// If not explicitly requested (or set in the handler) the start is set to 0
	assertEquals(0, documents.getStart());
	
	// Total number of documents found must be equals to all documents we previously indexed
	assertEquals(sampleData().size(), documents.getNumFound());
	
	// Page size must be 5, as requested
	assertEquals(5, documents.size());
}
 
Example 13
Source File: SolrController.java    From Spring-Boot-Book with Apache License 2.0 4 votes vote down vote up
@RequestMapping("/queryAll")
    public Object queryAll() throws IOException, SolrServerException {


        //第二种方式
        SolrQuery solrQuery = new SolrQuery();
        // 设置默认搜索域
        solrQuery.setQuery("*:*");
//        solrQuery.addField("*");
        solrQuery.set("q", "知然");
        solrQuery.add("q", "name:然");
        // 设置返回结果的排序规则
        solrQuery.setSort("id", SolrQuery.ORDER.asc);
        //设置查询的条数
        solrQuery.setRows(50);
        //设置查询的开始
        solrQuery.setStart(0);
        // 设置分页参数
        solrQuery.setStart(0);
        solrQuery.setRows(20);
        //设置高亮
        solrQuery.setHighlight(true);
        //设置高亮的字段
        solrQuery.addHighlightField("name");
        //设置高亮的样式
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");
        System.out.println(solrQuery);
        QueryResponse response = solrClient.query(solrQuery);
        //返回高亮显示结果
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        //response.getResults();查询返回的结果

        SolrDocumentList documentList = response.getResults();
        long numFound = documentList.getNumFound();
        System.out.println("总共查询到的文档数量: " + numFound);
        for (SolrDocument solrDocument : documentList) {
            System.out.println("solrDocument==============" + solrDocument);
            System.out.println("solrDocument==============" + solrDocument.get("name"));
        }
        return highlighting;
    }
 
Example 14
Source File: SolrControllerTest.java    From Spring-Boot-Book with Apache License 2.0 4 votes vote down vote up
@Test
    public void queryAll() throws IOException, SolrServerException {


        //第二种方式
        SolrQuery solrQuery = new SolrQuery();
        // 设置默认搜索域
        solrQuery.setQuery("*:*");
//        solrQuery.addField("*");
        solrQuery.set("q", "知然");
        solrQuery.add("q", "name:然");
        // 设置返回结果的排序规则
        solrQuery.setSort("id", SolrQuery.ORDER.asc);
        //设置查询的条数
        solrQuery.setRows(50);
        //设置查询的开始
        solrQuery.setStart(0);
        // 设置分页参数
        solrQuery.setStart(0);
        solrQuery.setRows(20);
        //设置高亮
        solrQuery.setHighlight(true);
        //设置高亮的字段
        solrQuery.addHighlightField("name");
        //设置高亮的样式
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");
        System.out.println(solrQuery);
        QueryResponse response = solrClient.query(solrQuery);
        //返回高亮显示结果
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        //response.getResults();查询返回的结果

        SolrDocumentList documentList = response.getResults();
        long numFound = documentList.getNumFound();
        System.out.println("总共查询到的文档数量: " + numFound);
        for (SolrDocument solrDocument : documentList) {
            System.out.println(solrDocument);
            System.out.println(solrDocument.get("name"));
        }
        System.out.println(highlighting);
    }
 
Example 15
Source File: SegmentTerminateEarlyTestState.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
void queryTimestampDescendingSegmentTerminateEarlyYes(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);
  final int rowsWanted = 1;
  query.setRows(rowsWanted);
  final Boolean shardsInfoWanted = (rand.nextBoolean() ? null : rand.nextBoolean());
  if (shardsInfoWanted != null) {
    query.set(ShardParams.SHARDS_INFO, shardsInfoWanted.booleanValue());
  }
  query.set(CommonParams.SEGMENT_TERMINATE_EARLY, true);
  final QueryResponse rsp = cloudSolrClient.query(query);
  // check correctness of the results count
  TestSegmentSorting.assertTrue("numFound", rowsWanted <= rsp.getResults().getNumFound());
  TestSegmentSorting.assertTrue("numFound", rsp.getResults().getNumFound() <= numDocs/2);
  // 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.assertNotNull("responseHeader.segmentTerminatedEarly missing in "+rsp.getResponseHeader(),
      rsp.getResponseHeader().get(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY));
  TestSegmentSorting.assertTrue("responseHeader.segmentTerminatedEarly missing/false 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;
      }
    }
    // check segmentTerminatedEarly flag within shards info
    TestSegmentSorting.assertTrue(segmentTerminatedEarlyShardsCount+" shards reported "+SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY,
        (0<segmentTerminatedEarlyShardsCount));
  }
}
 
Example 16
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);
  }
}