org.apache.solr.client.solrj.response.QueryResponse Java Examples

The following examples show how to use org.apache.solr.client.solrj.response.QueryResponse. 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: DocumentShrinker.java    From thoth with BSD 3-Clause Clear License 6 votes vote down vote up
/**
 * Tag slower documents and add them to the shrank core
 */
private void tagAndAddSlowThothDocuments() throws IOException, SolrServerException {
  // Query to return top MAX_NUMBER_SLOW_THOTH_DOCS slower thoth documents
  QueryResponse qr = realTimeServer.query(
      new SolrQuery()
          .setQuery(createThothDocsAggregationQuery())
          .addSort(QTIME, SolrQuery.ORDER.desc)
          .setRows(MAX_NUMBER_SLOW_THOTH_DOCS)
  );

  for (SolrDocument solrDocument: qr.getResults()){
    SolrInputDocument si = ClientUtils.toSolrInputDocument(solrDocument);
    // Remove old ID and version
    si.removeField(ID);
    si.removeField("_version_");
    // Tag document as slow
    si.addField(SLOW_QUERY_DOCUMENT, true);
    LOG.debug("Adding slow query document for server " + serverDetail.getName());
    shrankServer.add(si);
  }
}
 
Example #2
Source File: SolrExampleTests.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testChineseDefaults() throws Exception {
  SolrClient client = getSolrClient();
  // Empty the database...
  client.deleteByQuery("*:*");// delete everything!
  client.commit();
  assertNumFound( "*:*", 0 ); // make sure it got in

  // Beijing medical University
  UpdateRequest req = new UpdateRequest();
  SolrInputDocument doc = new SolrInputDocument();
  doc.addField("id", "42");
  doc.addField("text", "北京医科大学");
  req.add(doc);

  req.setAction(ACTION.COMMIT, true, true );
  req.process( client );

  // Beijing university should match:
  SolrQuery query = new SolrQuery("北京大学");
  QueryResponse rsp = client.query( query );
  assertEquals(1, rsp.getResults().getNumFound());
}
 
Example #3
Source File: JsonQueryRequestFacetingIntegrationTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testFacetWithDomainWidenedUsingExcludeTagsToIgnoreFilters() throws Exception {
  final TermsFacetMap inStockFacet = new TermsFacetMap("cat")
      .setLimit(2);
  final TermsFacetMap allProductsFacet = new TermsFacetMap("cat")
      .setLimit(2).withDomain(new DomainMap().withTagsToExclude("on_shelf"));
  final Map<String, Object> taggedFilterMap = new HashMap<>();
  taggedFilterMap.put("#on_shelf", "inStock:true");
  final JsonQueryRequest request = new JsonQueryRequest()
      .setQuery("*:*")
      .withFilter(taggedFilterMap)
      .withFacet("in_stock_only", inStockFacet)
      .withFacet("all", allProductsFacet);

  QueryResponse response = request.process(cluster.getSolrClient(), COLLECTION_NAME);

  assertExpectedDocumentsFoundAndReturned(response, NUM_IN_STOCK, 10);
  final NestableJsonFacet topLevelFacetData = response.getJsonFacetingResponse();
  assertHasFacetWithBucketValues(topLevelFacetData,"in_stock_only",
      new FacetBucket("electronics",8),
      new FacetBucket("currency", 4));
  assertHasFacetWithBucketValues(topLevelFacetData  ,"all",
      new FacetBucket("electronics",12),
      new FacetBucket("currency", 4));
}
 
Example #4
Source File: CaseController.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@GetMapping("/healthcheck")
public String healthcheck() throws Exception {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set(CommonParams.Q, "*:*");
    params.set(CommonParams.OMIT_HEADER, true);

    HttpSolrClient client = getClient();
    try {
        QueryResponse response = client.query(collection, params);
        if (response.getStatus() == 0) {
            return "Success";
        }
        throw new Exception(response.toString());
    } catch (Exception e) {
        throw e;
    }
}
 
Example #5
Source File: MtasSolrTestSearchConsistency.java    From mtas with Apache License 2.0 6 votes vote down vote up
/**
 * Cql query parser.
 *
 * @throws IOException
 *           Signals that an I/O exception has occurred.
 */
@org.junit.Test
public void cqlQueryParser() throws IOException {
  ModifiableSolrParams params = new ModifiableSolrParams();
  params.set("q",
      "{!mtas_cql field=\"mtas\" query=\"[pos=\\\"ADJ\\\"]{2}[pos=\\\"N\\\"]\"}");
  try {
    QueryResponse qResp1 = server.query("collection1", params);
    QueryResponse qResp2 = server.query("collection2", params);
    QueryResponse qResp3 = server.query("collection3", params);
    SolrDocumentList docList1 = qResp1.getResults();
    SolrDocumentList docList2 = qResp2.getResults();
    SolrDocumentList docList3 = qResp3.getResults();
    assertFalse(docList1.isEmpty());
    assertEquals(docList1.size(), (long) docList2.size() + docList3.size());
  } catch (SolrServerException e) {
    throw new IOException(e.getMessage(), e);
  }
}
 
Example #6
Source File: Searcher.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected List<String> executeQuery(SolrQuery solrQuery) throws ApsSystemException {
  	List<String> contentsId = new ArrayList<String>();
  	try {
	HttpClient httpClient = new DefaultHttpClient();
	SolrServer solr = new HttpSolrServer(this.getSolrUrl(), httpClient, new XMLResponseParser());
	QueryResponse rsp = solr.query(solrQuery);
          SolrDocumentList solrDocumentList = rsp.getResults();
          for (SolrDocument doc : solrDocumentList) {
		String id = (String) doc.getFieldValue(CmsSearchEngineManager.CONTENT_ID_FIELD_NAME); //id is the uniqueKey field
              contentsId.add(id);
          }
  	} catch (SolrServerException e) {
	throw new ApsSystemException("Error on solr server", e);
} catch (Throwable t) {
  		throw new ApsSystemException("Error extracting response", t);
  	}
  	return contentsId;
  }
 
Example #7
Source File: ItemSearchServiceLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenSearchingByBasicQuery_thenAllMatchingItemsShouldAvialble() throws Exception {
    itemSearchService.index("hm0001", "Brand1 Washing Machine", "Home Appliances", 450f);
    itemSearchService.index("hm0002", "Brand1 Refrigerator", "Home Appliances", 450f);
    itemSearchService.index("hm0003", "LED TV 32", "Brand1 Home Appliances", 450f);

    SolrQuery query = new SolrQuery();
    query.setQuery("brand1");
    query.setStart(0);
    query.setRows(10);

    QueryResponse response = solrClient.query(query);
    List<Item> items = response.getBeans(Item.class);

    assertEquals(3, items.size());

}
 
Example #8
Source File: DistributedAlfrescoSolrFacetingIT.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void fieldFaceting_mincountSetZero_shouldReturnFacetsMincountOne() throws Exception
{
    String expectedContentFacetField = "{http://www.alfresco.org/model/content/1.0}content:[contenttwo (4), contentone (1)]";
    String expectedNameFacetField = "{http://www.alfresco.org/model/content/1.0}name:[nametwo (4), nameone (1)]";

    String jsonQuery = "{\"query\":\"(suggest:a)\",\"locales\":[\"en\"], \"templates\": [{\"name\":\"t1\", \"template\":\"%cm:content\"}], \"authorities\": [\"joel\"], \"tenants\": []}";
    putHandleDefaults();

    QueryResponse queryResponse = query(getDefaultTestClient(), true, jsonQuery,
        params("qt", "/afts", "shards.qt", "/afts", "start", "0", "rows", "0", "fl", "score,id", "facet", "true",
            "facet.field", "{http://www.alfresco.org/model/content/1.0}content",
            "facet.field", "{http://www.alfresco.org/model/content/1.0}name",
            "facet.mincount", "0"));

    List<FacetField> facetFields = queryResponse.getFacetFields();
    FacetField contentFacetField = facetFields.get(0);
    Assert.assertThat(contentFacetField.toString(), is(expectedContentFacetField));
    FacetField nameFacetField = facetFields.get(1);
    Assert.assertThat(nameFacetField.toString(), is(expectedNameFacetField));
}
 
Example #9
Source File: SolrTemplate.java    From dubbox with Apache License 2.0 6 votes vote down vote up
private <T> SolrResultPage<T> createSolrResultPage(Query query, Class<T> clazz, QueryResponse response,
		Map<String, Object> objectsName) {
	List<T> beans = convertQueryResponseToBeans(response, clazz);
	SolrDocumentList results = response.getResults();
	long numFound = results == null ? 0 : results.getNumFound();
	Float maxScore = results == null ? null : results.getMaxScore();

	Pageable pageRequest = query.getPageRequest();

	SolrResultPage<T> page = new SolrResultPage<T>(beans, pageRequest, numFound, maxScore);

	page.setFieldStatsResults(
			ResultHelper.convertFieldStatsInfoToFieldStatsResultMap(response.getFieldStatsInfo()));
	page.setGroupResults(
			ResultHelper.convertGroupQueryResponseToGroupResultMap(query, objectsName, response, this, clazz));

	return page;
}
 
Example #10
Source File: SolrSearchServer.java    From vind with Apache License 2.0 6 votes vote down vote up
@Override
public SuggestionResult execute(ExecutableSuggestionSearch search, DocumentFactory assets,DocumentFactory childFactory) {
    SolrQuery query = buildSolrQuery(search, assets, childFactory);

    try {
        log.debug(">>> query({})", query.toString());
        QueryResponse response = solrClient.query(query, REQUEST_METHOD);
        if(response!=null){
            return SolrUtils.Result.buildSuggestionResult(response, assets, childFactory, search.getSearchContext());
        }else {
            log.error("Null result from SolrClient");
            throw new SolrServerException("Null result from SolrClient");
        }

    } catch (SolrServerException | IOException e) {
        log.error("Cannot execute suggestion query");
        throw new SearchServerException("Cannot execute suggestion query", e);
    }
}
 
Example #11
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 #12
Source File: AlfrescoFieldMapperTransformerIT.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void transformDocument_noDocTransformer_shouldReturnBasicFields() throws Exception 
{
    putHandleDefaults();
    //Test 1: Running a simple query without invoking AlfrescoFieldMapperTransformer, expected to see id,DBID and _version_
    QueryResponse resp = query(getDefaultTestClient(), true, ALFRESCO_JSON, params("q", "*", "qt", "/afts", "shards.qt", "/afts", "sort", "id asc"));
    assertNotNull(resp);
    SolrDocumentList results = resp.getResults();
    assertEquals("Expecting 5 rows",5, results.size());
    SolrDocument doc = results.get(0);
    assertEquals(3, doc.size());
    assertNotNull(doc);
    String id = (String) doc.get("id");
    assertNotNull(id);
    Long version = (Long) doc.get("_version_");
    assertNotNull(version);
    Long dbid = (Long) doc.get("DBID");
    assertNotNull(dbid);
    //Not expected to see below as part of the solr response.
    String title = (String) doc.get("cm:title");
    assertNull(title);
    String owner = (String) doc.get("OWNER");
    assertNull(owner);
}
 
Example #13
Source File: MCROAISolrSearcher.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Optional<Header> getHeader(String mcrId) {
    SolrQuery query = getBaseQuery(CommonParams.FQ);
    query.set(CommonParams.Q, "id:" + MCRSolrUtils.escapeSearchValue(mcrId));
    query.setRows(1);
    // do the query
    SolrClient solrClient = MCRSolrClientFactory.getMainSolrClient();
    try {
        QueryResponse response = solrClient.query(query);
        SolrDocumentList results = response.getResults();
        if (!results.isEmpty()) {
            return Optional.of(toHeader(results.get(0), getSetResolver(results)));
        }
    } catch (Exception exc) {
        LOGGER.error("Unable to handle solr request", exc);
    }
    return Optional.empty();
}
 
Example #14
Source File: TestUtils.java    From hbase-indexer with Apache License 2.0 6 votes vote down vote up
public static void validateSolrServerDocumentCount(File solrHomeDir, FileSystem fs, Path outDir, int expectedDocs, int expectedShards)
    throws IOException, SolrServerException {
  
  long actualDocs = 0;
  int actualShards = 0;
  for (FileStatus dir : fs.listStatus(outDir)) { // for each shard
    if (dir.getPath().getName().startsWith("part") && dir.isDirectory()) {
      actualShards++;
      EmbeddedSolrServer solr = createEmbeddedSolrServer(
          solrHomeDir, fs, dir.getPath());
      
      try {
        SolrQuery query = new SolrQuery();
        query.setQuery("*:*");
        QueryResponse resp = solr.query(query);
        long numDocs = resp.getResults().getNumFound();
        actualDocs += numDocs;
      } finally {
        solr.close();
      }
    }
  }
  assertEquals(expectedShards, actualShards);
  assertEquals(expectedDocs, actualDocs);
}
 
Example #15
Source File: JsonRequestApiTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testTermsFacet2() throws Exception {
  SolrClient solrClient = cluster.getSolrClient();

  //tag::solrj-json-terms-facet-2[]
  final TermsFacetMap categoryFacet = new TermsFacetMap("cat").setLimit(5);
  final JsonQueryRequest request = new JsonQueryRequest()
      .setQuery("*:*")
      .withFacet("categories", categoryFacet);
  QueryResponse queryResponse = request.process(solrClient, COLLECTION_NAME);
  //end::solrj-json-terms-facet-2[]

  assertEquals(0, queryResponse.getStatus());
  assertEquals(32, queryResponse.getResults().getNumFound());
  assertEquals(10, queryResponse.getResults().size());
  final NestableJsonFacet topLevelFacetingData = queryResponse.getJsonFacetingResponse();
  assertHasFacetWithBucketValues(topLevelFacetingData,"categories",
      new FacetBucket("electronics",12),
      new FacetBucket("currency", 4),
      new FacetBucket("memory", 3),
      new FacetBucket("connector", 2),
      new FacetBucket("graphics card", 2));
}
 
Example #16
Source File: JsonQueryRequestFacetingIntegrationTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testRangeFacetWithOtherBucketsRequested() throws Exception {
  final JsonQueryRequest request = new JsonQueryRequest()
      .setQuery("*:*")
      .withFacet("price_range",
          new RangeFacetMap("price", 0, 100, 20)
              .setOtherBuckets(RangeFacetMap.OtherBuckets.ALL)
      );

  QueryResponse response = request.process(cluster.getSolrClient(), COLLECTION_NAME);
  final NestableJsonFacet topLevelFacetData = response.getJsonFacetingResponse();

  assertHasFacetWithBucketValues(topLevelFacetData, "price_range",
      new FacetBucket(0.0f, 5),
      new FacetBucket(20.0f, 0),
      new FacetBucket(40.0f, 0),
      new FacetBucket(60.0f, 1),
      new FacetBucket(80.0f, 1));
  assertEquals(0, topLevelFacetData.getBucketBasedFacets("price_range").getBefore());
  assertEquals(9, topLevelFacetData.getBucketBasedFacets("price_range").getAfter());
  assertEquals(7, topLevelFacetData.getBucketBasedFacets("price_range").getBetween());
}
 
Example #17
Source File: SolrExampleTests.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetNullUpdates() throws Exception {
  SolrClient solrClient = getSolrClient();
  SolrInputDocument doc = new SolrInputDocument();
  doc.addField("id", "testSetNullUpdates");
  doc.addField("single_s", "test-value");
  doc.addField("multi_ss", Arrays.asList("first", "second"));
  solrClient.add(doc);
  solrClient.commit(true, true);
  doc.removeField("single_s");
  doc.removeField("multi_ss");
  Map<String, Object> map = Maps.newHashMap();
  map.put("set", null);
  doc.addField("multi_ss", map);
  solrClient.add(doc);
  solrClient.commit(true, true);
  QueryResponse response = solrClient.query(new SolrQuery("id:testSetNullUpdates"));
  assertNotNull("Entire doc was replaced because null update was not written", response.getResults().get(0).getFieldValue("single_s"));
  assertNull("Null update failed. Value still exists in document", response.getResults().get(0).getFieldValue("multi_ss"));
}
 
Example #18
Source File: CloudSolrClientTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testOverwriteOption() throws Exception {

  CollectionAdminRequest.createCollection("overwrite", "conf", 1, 1)
      .processAndWait(cluster.getSolrClient(), TIMEOUT);
  cluster.waitForActiveCollection("overwrite", 1, 1);
  
  new UpdateRequest()
      .add("id", "0", "a_t", "hello1")
      .add("id", "0", "a_t", "hello2")
      .commit(cluster.getSolrClient(), "overwrite");

  QueryResponse resp = cluster.getSolrClient().query("overwrite", new SolrQuery("*:*"));
  assertEquals("There should be one document because overwrite=true", 1, resp.getResults().getNumFound());

  new UpdateRequest()
      .add(new SolrInputDocument(id, "1", "a_t", "hello1"), /* overwrite = */ false)
      .add(new SolrInputDocument(id, "1", "a_t", "hello2"), false)
      .commit(cluster.getSolrClient(), "overwrite");
    
  resp = getRandomClient().query("overwrite", new SolrQuery("*:*"));
  assertEquals("There should be 3 documents because there should be two id=1 docs due to overwrite=false", 3, resp.getResults().getNumFound());

}
 
Example #19
Source File: SolrConnector.java    From TagRec with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public List<Tweet> getTrainTweetObjects(SolrConnector trainConnector, int hours) {
	List<Tweet> tweetObjects = new ArrayList<Tweet>();
	
	SolrQuery solrParams = new SolrQuery();
	solrParams.set("q", "*:*");
	solrParams.set("rows", Integer.MAX_VALUE);
	QueryResponse r = null;
	try {
		r = this.server.query(solrParams);
		SolrDocumentList docs = r.getResults();
		for (SolrDocument d : docs) {
			String userId = (String) d.get("userid");
			String text = trainConnector.getTweetTextOfLastHours(userId, hours);
			tweetObjects.add(new Tweet((String) d.get("id"), userId, text, (String) d.get("timestamp"), new LinkedHashSet<String>((List<String>) d.get("hashtags"))));
		}
	} catch (SolrServerException e) {
		e.printStackTrace();
	}
	
	return tweetObjects;
}
 
Example #20
Source File: MavenCentralSearchApiServiceImpl.java    From artifact-listener with Apache License 2.0 5 votes vote down vote up
@Override
public long countArtifacts(String global, String groupId, String artifactId) throws ServiceException {
	String query = getSearchArtifactsQuery(global, groupId, artifactId);
	if (!StringUtils.hasText(query)) {
		return 0;
	}
	SolrQuery solrQuery = new SolrQuery(query);
	
	QueryResponse response = query(solrQuery, 0, 0);
	return response.getResults().getNumFound();
}
 
Example #21
Source File: SolrSearchDao.java    From metron with Apache License 2.0 5 votes vote down vote up
protected Map<String, Map<String, Long>> getFacetCounts(List<String> fields,
    QueryResponse solrResponse) {
  Map<String, Map<String, Long>> fieldCounts = new HashMap<>();
  for (String field : fields) {
    Map<String, Long> valueCounts = new HashMap<>();
    FacetField facetField = solrResponse.getFacetField(field);
    for (Count facetCount : facetField.getValues()) {
      valueCounts.put(facetCount.getName(), facetCount.getCount());
    }
    fieldCounts.put(field, valueCounts);
  }
  return fieldCounts;
}
 
Example #22
Source File: SolrExampleTests.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings({"unchecked"})
public void testUpdateMultiValuedField() throws Exception {
  SolrClient solrClient = getSolrClient();
  SolrInputDocument doc = new SolrInputDocument();
  doc.addField("id", "123");
  solrClient.add(doc);
  solrClient.commit(true, true);
  QueryResponse response = solrClient.query(new SolrQuery("id:123"));
  assertEquals("Failed to add doc to cloud server", 1, response.getResults().getNumFound());

  Map<String, List<String>> operation = new HashMap<>();
  operation.put("set", Arrays.asList("first", "second", "third"));
  doc.addField("multi_ss", operation);
  solrClient.add(doc);
  solrClient.commit(true, true);
  response = solrClient.query(new SolrQuery("id:123"));
  assertTrue("Multi-valued field did not return a collection", response.getResults().get(0).get("multi_ss") instanceof List);
  List<String> values = (List<String>) response.getResults().get(0).get("multi_ss");
  assertEquals("Field values was not updated with all values via atomic update", 3, values.size());

  operation.clear();
  operation.put("add", Arrays.asList("fourth", "fifth"));
  doc.removeField("multi_ss");
  doc.addField("multi_ss", operation);
  solrClient.add(doc);
  solrClient.commit(true, true);
  response = solrClient.query(new SolrQuery("id:123"));
  values = (List<String>) response.getResults().get(0).get("multi_ss");
  assertEquals("Field values was not updated with all values via atomic update", 5, values.size());
}
 
Example #23
Source File: CloudMLTQParserTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testHighDFValue() throws Exception {

  // Test out a high value of df and make sure nothing matches.
  QueryResponse queryResponse = cluster.getSolrClient().query(COLLECTION,
      new SolrQuery("{!mlt qf=lowerfilt_u mindf=20 mintf=1}3"));
  SolrDocumentList solrDocuments = queryResponse.getResults();
  assertEquals("Expected to match 0 documents with a mindf of 20 but found more", solrDocuments.size(), 0);

}
 
Example #24
Source File: TestDistributedSearch.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/** comparing results with facet.method=uif */
private void queryAndCompareUIF(Object ... params) throws Exception {
  final QueryResponse expect = query(params);
  
  final Object[] newParams = Arrays.copyOf(params, params.length+2);
  newParams[newParams.length-2] = "facet.method";
  newParams[newParams.length-1] = "uif";
  final QueryResponse uifResult = query(newParams);
  compareResponses(expect, uifResult);
}
 
Example #25
Source File: PeerSyncWithBufferUpdatesTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
void validateQACResponse(Set<Integer> docsAdded, QueryResponse qacResponse) {
  Set<Integer> qacDocs = new LinkedHashSet<>();
  for (int i=0; i<qacResponse.getResults().size(); i++) {
    qacDocs.add(Integer.parseInt(qacResponse.getResults().get(i).getFieldValue("id").toString()));
  }
  assertEquals(docsAdded, qacDocs);
  assertEquals(docsAdded.size(), qacResponse.getResults().getNumFound());
}
 
Example #26
Source File: RangeFacetCloudTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testRangeWithOldIntervalFormat() throws Exception {
  for (boolean doSubFacet : Arrays.asList(false, true)) {
    final Integer subFacetLimit = pickSubFacetLimit(doSubFacet);
    final CharSequence subFacet = makeSubFacet(subFacetLimit);
    for (boolean incUpper : Arrays.asList(false, true)) {
      String incUpperStr = incUpper? "]\"":")\"";
      final SolrQuery solrQuery = new SolrQuery
          ("q", "*:*", "rows", "0", "json.facet",
              "{ foo:{ type:range, field:" + INT_FIELD + " ranges:[{range:\"[1,2"+ incUpperStr+ "}," +
                  "{range:\"[2,3"+ incUpperStr +"},{range:\"[3,4"+ incUpperStr +"},{range:\"[4,5"+ incUpperStr+"}]"
                  + subFacet + " } }");

      final QueryResponse rsp = cluster.getSolrClient().query(solrQuery);
      try {
        @SuppressWarnings({"unchecked"})
        final NamedList<Object> foo = ((NamedList<NamedList<Object>>) rsp.getResponse().get("facets")).get("foo");
        @SuppressWarnings({"unchecked"})
        final List<NamedList<Object>> buckets = (List<NamedList<Object>>) foo.get("buckets");

        assertEquals("num buckets", 4, buckets.size());
        for (int i = 0; i < 4; i++) {
          String expectedVal = "[" + (i + 1) + "," + (i + 2) + (incUpper? "]": ")");
          ModelRange modelVals = incUpper? modelVals(i+1, i+2) : modelVals(i+1);
          assertBucket("bucket#" + i, expectedVal, modelVals, subFacetLimit, buckets.get(i));
        }
      } catch (AssertionError | RuntimeException ae) {
        throw new AssertionError(solrQuery.toString() + " -> " + rsp.toString() + " ===> " + ae.getMessage(), ae);
      }
    }
  }
}
 
Example #27
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 #28
Source File: MergeStrategyTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void assertOrder(QueryResponse rsp, String ... docs) throws Exception {
  SolrDocumentList list = rsp.getResults();
  for(int i=0; i<docs.length; i++) {
    SolrDocument doc = list.get(i);
    Object o = doc.getFieldValue("id");
    if(!docs[i].equals(o)) {
      throw new Exception("Order is not correct:"+o+"!="+docs[i]);
    }
  }
}
 
Example #29
Source File: CurrencyRangeFacetCloudTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testJsonFacetCleanErrorOnMissmatchCurrency() {
  final String expected = "Cannot compare CurrencyValues when their currencies are not equal";
  ignoreException(expected);
  
  // test to check clean error when start/end have diff currency (json.facet)
  final SolrQuery solrQuery = new SolrQuery("q", "*:*", "json.facet",
                                            "{ x:{ type:range, field:"+FIELD+", " +
                                            "      start:'0,EUR', gap:'10,EUR', end:'100,USD' } }");
  final SolrException ex = expectThrows(SolrException.class, () -> {
      final QueryResponse rsp = cluster.getSolrClient().query(solrQuery);
    });
  assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, ex.code());
  assertTrue(ex.getMessage(), ex.getMessage().contains(expected));
}
 
Example #30
Source File: JsonQueryRequestIntegrationTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueriesCanUseExpandedSyntax() throws Exception {
  //Construct a tree representing the JSON: {lucene: {df:'genre_s', 'query': 'scifi'}}
  final Map<String, Object> queryMap = new HashMap<>();
  final Map<String, Object> luceneQueryParamMap = new HashMap<>();
  queryMap.put("lucene", luceneQueryParamMap);
  luceneQueryParamMap.put("df", "genre_s");
  luceneQueryParamMap.put("query", "scifi");

  final JsonQueryRequest simpleQuery = new JsonQueryRequest()
      .setQuery(queryMap);
  QueryResponse queryResponse = simpleQuery.process(cluster.getSolrClient(), COLLECTION_NAME);
  assertEquals(0, queryResponse.getStatus());
  assertEquals(NUM_SCIFI_BOOKS, queryResponse.getResults().getNumFound());
}