Java Code Examples for org.apache.solr.common.SolrDocumentList#get()

The following examples show how to use org.apache.solr.common.SolrDocumentList#get() . 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: StandardSearchEngine.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Hit getHit(long id) {
	SolrQuery query = new SolrQuery();
	query.setQuery("id:" + id);
	query.setFields("*");
	try {
		QueryResponse rsp = server.query(query);
		SolrDocumentList docs = rsp.getResults();
		if (docs.size() < 1)
			return null;

		SolrDocument doc = docs.get(0);
		Hit hit = Hits.toHit(doc);
		hit.setContent((String) doc.getFieldValue(HitField.CONTENT.getName()));
		return hit;
	} catch (Throwable e) {
		log.error(e.getMessage());
	}
	return null;
}
 
Example 2
Source File: SolrTestCaseJ4.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Fails if the number of documents in the given SolrDocumentList differs
 * from the given number of expected values, or if any of the values in the
 * given field don't match the expected values in the same order.
 */
public static void assertFieldValues(SolrDocumentList documents, String fieldName, Object... expectedValues) {
  if (documents.size() != expectedValues.length) {
    fail("Number of documents (" + documents.size()
        + ") is different from number of expected values (" + expectedValues.length);
  }
  for (int docNum = 1 ; docNum <= documents.size() ; ++docNum) {
    SolrDocument doc = documents.get(docNum - 1);
    Object expected = expectedValues[docNum - 1];
    Object actual = doc.get(fieldName);
    if ((null == expected && null != actual) ||
        (null != expected && null == actual) ||
        (null != expected && null != actual && !expected.equals(actual))) {
      fail("Unexpected " + fieldName + " field value in document #" + docNum
          + ": expected=[" + expected + "], actual=[" + actual + "]");
    }
  }
}
 
Example 3
Source File: TestMerge.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
/**
 * A dynamic copy field should be filled as normal.
 */
@Test
public void testDynamicCopyField() throws Exception {
  try (SolrCore core = h.getCoreContainer().getCore("merge")) {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add("q", "*:*");
    params.add("sort", "letter asc");
    params.add("fl", "copyx");

    SolrDocumentList docs = queryDocs(core, "merge", params);
    assertEquals(3, docs.size());
    
    SolrDocument doc0 = docs.get(0);
    assertEquals("plugh", doc0.getFieldValue("copyx"));
    
    SolrDocument doc1 = docs.get(1);
    assertEquals("fee", doc1.getFieldValue("copyx"));
    
    SolrDocument doc2 = docs.get(2);
    assertEquals("plover", doc2.getFieldValue("copyx"));
  }   
}
 
Example 4
Source File: TestMerge.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
/**
 * Copy-field directives in the aggregator schema should be respected.
 */
@Test
public void testCopyFields() throws Exception {
  try (SolrCore core = h.getCoreContainer().getCore("merge")) {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add("q", "*:*");
    params.add("sort", "letter asc");
    params.add("fl", "*");

    SolrDocumentList docs = queryDocs(core, "merge", params);
    assertEquals(3, docs.size());
    
    SolrDocument doc0 = docs.get(0);
    assertEquals("x", doc0.getFieldValue("copy"));
    assertEquals(new HashSet<String>(Arrays.asList("A", "D", "E", "x")), doc0.getFieldValue("multicopy"));
    
    SolrDocument doc1 = docs.get(1);
    assertEquals("y", doc1.getFieldValue("copy"));
    assertEquals(new HashSet<String>(Arrays.asList("B", "y")), doc1.getFieldValue("multicopy"));
    
    SolrDocument doc2 = docs.get(2);
    assertEquals("z", doc2.getFieldValue("copy"));
    assertEquals(new HashSet<String>(Arrays.asList("C", "Q", "z")), doc2.getFieldValue("multicopy"));
  }   
}
 
Example 5
Source File: TestMerge.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
/**
 * All values from shard's multi-valued fields should be present in the merged field.
 */
@Test
public void testMultiValued() throws Exception {
  try (SolrCore core = h.getCoreContainer().getCore("merge")) {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add("q", "*:*");
    params.add("sort", "letter asc");
    params.add("fl", "text");

    SolrDocumentList docs = queryDocs(core, "merge", params);
    assertEquals(3, docs.size());
    
    SolrDocument doc0 = docs.get(0);
    assertEquals(new HashSet<String>(Arrays.asList("foo", "bar", "baz")), doc0.getFieldValue("text"));
  }   
}
 
Example 6
Source File: TestMerge.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
/**
 * A dynamic field defined in the aggregator schema should accept values.
 */
@Test
public void testDynamicField() throws Exception {
  try (SolrCore core = h.getCoreContainer().getCore("merge")) {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add("q", "*:*");
    params.add("sort", "letter asc");
    params.add("fl", "xyzzy");

    SolrDocumentList docs = queryDocs(core, "merge", params);
    assertEquals(3, docs.size());
    
    SolrDocument doc0 = docs.get(0);
    assertEquals("plugh", doc0.getFieldValue("xyzzy"));
    
    SolrDocument doc1 = docs.get(1);
    assertEquals("fee", doc1.getFieldValue("xyzzy"));
    
    SolrDocument doc2 = docs.get(2);
    assertEquals("plover", doc2.getFieldValue("xyzzy"));
  }   
}
 
Example 7
Source File: TestMerge.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
/**
 * Default values in the schema should be used if no value is returned from shards.
 */
@Test
public void testDefaultValue() throws Exception {
  try (SolrCore core = h.getCoreContainer().getCore("merge")) {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add("q", "*:*");
    params.add("sort", "letter asc");
    params.add("fl", "default");

    SolrDocumentList docs = queryDocs(core, "merge", params);
    assertEquals(3, docs.size());
    
    SolrDocument doc0 = docs.get(0);
    assertEquals("foo", doc0.getFieldValue("default"));
  }   
}
 
Example 8
Source File: TestMerge.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
/**
 * Fields should not be returned if they are non-stored, even if asked for.
 */
@Test
public void testNonStored() throws Exception {
  try (SolrCore core = h.getCoreContainer().getCore("merge")) {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add("q", "*:*");
    params.add("sort", "letter asc");
    params.add("fl", "required");

    SolrDocumentList docs = queryDocs(core, "merge", params);
    assertEquals(3, docs.size());
    
    SolrDocument doc0 = docs.get(0);
    assertNull(doc0.getFieldValue("required"));
  }   
}
 
Example 9
Source File: DistributedAlfrescoSolrFingerPrintIT.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testFingerPrint3() throws Exception
{
    putHandleDefaults();
    QueryResponse response = query(getDefaultTestClient(), true,
        "{\"locales\":[\"en\"], \"templates\": [{\"name\":\"t1\", \"template\":\"%cm:content\"}], \"authorities\": [\"joel\"], \"tenants\": []}",
        params("q", "FINGERPRINT:" + NODES[0].getId()+"_45",
            "qt", "/afts",
            "shards.qt", "/afts",
            "start", "0",
            "fl", "DBID,score",
            "rows", "100"));

    SolrDocumentList docs = response.getResults();
    assertEquals(3, docs.getNumFound());
    SolrDocument doc0 = docs.get(0);
    long dbid0 = (long)doc0.getFieldValue("DBID");
    assertEquals(dbid0, NODES[0].getId());

    SolrDocument doc1 = docs.get(1);
    long dbid1 = (long)doc1.getFieldValue("DBID");
    assertEquals(dbid1, NODES[2].getId());

    SolrDocument doc2 = docs.get(2);
    long dbid2 = (long)doc2.getFieldValue("DBID");
    assertEquals(dbid2, NODES[1].getId());
}
 
Example 10
Source File: TestCloudPseudoReturnFields.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testFilterAndOneRealFieldRTG() throws Exception {
  SolrParams params = params("fl","id,val_i",
                             "fq","{!field f='subject' v=$my_var}",
                             "my_var","uncommitted");
  SolrDocumentList docs = getRandClient(random()).getById(Arrays.asList("42","99"), params);
  final String msg = params + " => " + docs;
  assertEquals(msg, 1, docs.size());
  assertEquals(msg, 1, docs.getNumFound());
  
  SolrDocument doc = docs.get(0);
  assertEquals(msg, 2, doc.size());
  assertEquals(msg, "99", doc.getFieldValue("id"));
  assertEquals(msg, 1, doc.getFieldValue("val_i"));
}
 
Example 11
Source File: DistributedAlfrescoSolrFingerPrintIT.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testFingerPrint() throws Exception
{
    putHandleDefaults();
    QueryResponse response = query(getDefaultTestClient(), true,
                                   "{\"locales\":[\"en\"], \"templates\": [{\"name\":\"t1\", \"template\":\"%cm:content\"}], \"authorities\": [\"joel\"], \"tenants\": []}",
                                    params("q", "FINGERPRINT:"+ NODES[0].getId(),
                                            "qt", "/afts",
                                            "shards.qt", "/afts",
                                            "start", "0",
                                            "fl","DBID,score",
                                            "rows", "100"));

    SolrDocumentList docs = response.getResults();
    assertEquals(4, docs.getNumFound());
    SolrDocument doc0 = docs.get(0);
    long dbid0 = (long)doc0.getFieldValue("DBID");
    assertEquals(dbid0, NODES[0].getId());

    SolrDocument doc1 = docs.get(1);
    long dbid1 = (long)doc1.getFieldValue("DBID");
    assertEquals(dbid1, NODES[2].getId());

    SolrDocument doc2 = docs.get(2);
    long dbid2 = (long)doc2.getFieldValue("DBID");
    assertEquals(dbid2, NODES[1].getId());

    SolrDocument doc3 = docs.get(3);
    long dbid3 = (long)doc3.getFieldValue("DBID");
    assertEquals(dbid3, NODES[3].getId());
}
 
Example 12
Source File: DistributedAlfrescoSolrFingerPrintIT.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testFingerPrint6() throws Exception
{
    putHandleDefaults();
    QueryResponse response = query(getDefaultTestClient(), true,
        "{\"locales\":[\"en\"], \"templates\": [{\"name\":\"t1\", \"template\":\"%cm:content\"}], \"authorities\": [\"joel\"], \"tenants\": []}",
        params("q", "FINGERPRINT:" + NODES_METADATA[0].getNodeRef().getId() +"_45",
            "qt", "/afts",
            "shards.qt", "/afts",
            "start", "0",
            "fl", "DBID,score",
            "rows", "100"));

    SolrDocumentList docs = response.getResults();
    assertEquals(3, docs.getNumFound());
    SolrDocument doc0 = docs.get(0);
    long dbid0 = (long)doc0.getFieldValue("DBID");
    assertEquals(dbid0, NODES[0].getId());

    SolrDocument doc1 = docs.get(1);
    long dbid1 = (long)doc1.getFieldValue("DBID");
    assertEquals(dbid1, NODES[2].getId());

    SolrDocument doc2 = docs.get(2);
    long dbid2 = (long)doc2.getFieldValue("DBID");
    assertEquals(dbid2, NODES[1].getId());
}
 
Example 13
Source File: AlfrescoFieldMapperTransformerIT.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void transformDocument_docTransformerAndScoreRequested_shouldReturnScore() throws Exception
{
    putHandleDefaults();

    QueryResponse resp = query(getDefaultTestClient(), true, ALFRESCO_JSON, params("q", "*", "qt", "/afts", "shards.qt", "/afts","fl","cm_name, score, [fmap]", "sort", "id asc"));
    assertNotNull(resp);
    SolrDocumentList results = resp.getResults();
    SolrDocument docWithAllFields = results.get(0);
    assertEquals(2, docWithAllFields.size());
    assertNotNull(docWithAllFields.get("cm_name"));
    Float score = (Float) docWithAllFields.get("score");
    assertNotNull(score);
}
 
Example 14
Source File: TestCloudPseudoReturnFields.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testFunctionsAndExplicit() throws Exception {
  for (SolrParams p : Arrays.asList(params("q","*:*", "rows", "1", "fl","log(val_i),val_i"),
                                    params("q","*:*", "rows", "1", "fl","log(val_i)", "fl","val_i"))) {
    SolrDocumentList docs = assertSearch(p);
    assertEquals(p + " => " + docs, 5, docs.getNumFound());
    SolrDocument doc = docs.get(0); // doesn't really matter which one
    assertEquals(p + " => " + doc, 2, doc.size());
    assertTrue(p + " => " + doc, doc.getFieldValue("log(val_i)") instanceof Double);
    assertTrue(p + " => " + doc, doc.getFieldValue("val_i") instanceof Integer);
  }
}
 
Example 15
Source File: AlfrescoFieldMapperTransformerIT.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void transformDocument_docTransformerIsUsedWithOtherTransformer_shouldExecuteBothTranformers() throws Exception
{
    putHandleDefaults();

    QueryResponse resp = query(getDefaultTestClient(), true, ALFRESCO_JSON, params("q", "*", "qt", "/afts", "shards.qt", "/afts","fl","cm_title, [explain], [fmap]", "sort", "id asc"));
    assertNotNull(resp);
    SolrDocumentList results = resp.getResults();
    SolrDocument docWithAllFields = results.get(0);
    assertEquals(2, docWithAllFields.size());
    assertNotNull(docWithAllFields.get("cm_title"));
    assertNotNull(docWithAllFields.get("[explain]"));
}
 
Example 16
Source File: SolrBoltActionTest.java    From storm-solr with Apache License 2.0 5 votes vote down vote up
protected void doBoltActionTest() throws Exception {
  // Spring @Autowired property at runtime
  SolrBoltAction sba = new SolrBoltAction(cloudSolrClient);
  sba.setUpdateRequestStrategy(new DefaultUpdateRequestStrategy());
  sba.setMaxBufferSize(1); // to avoid buffering docs

  // Mock the Storm tuple
  String docId = "1";
  TestDoc testDoc = new TestDoc(docId, "foo", 10);
  Tuple mockTuple = mock(Tuple.class);
  when(mockTuple.size()).thenReturn(2);
  when(mockTuple.getString(0)).thenReturn(docId);
  when(mockTuple.getValue(1)).thenReturn(testDoc);
  SpringBolt.ExecuteResult result = sba.execute(mockTuple, null);
  assertTrue(result == SpringBolt.ExecuteResult.ACK);
  cloudSolrClient.commit();

  // verify the object to Solr mapping worked correctly using reflection and dynamic fields
  SolrQuery query = new SolrQuery("id:" + docId);
  QueryResponse qr = cloudSolrClient.query(query);
  SolrDocumentList results = qr.getResults();
  assertTrue(results.getNumFound() == 1);
  SolrDocument doc = results.get(0);
  assertNotNull(doc);
  assertEquals("foo", doc.getFirstValue("text_s"));
  assertEquals(new Integer(testDoc.number), doc.getFirstValue("number_i"));
  assertTrue(doc.getFirstValue("timestamp_tdt") != null);
}
 
Example 17
Source File: ServiceLogsManager.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
private Date getDocDateFromNextOrLastPage(ServiceLogRequest request, String keyword, boolean isNext, int currentPageNumber, int maxRows) {
  int lastOrFirstLogIndex;
  if (isNext) {
    lastOrFirstLogIndex = ((currentPageNumber + 1) * maxRows);
  } else {
    if (currentPageNumber == 0) {
      throw new NotFoundException("This is the first Page");
    }
    lastOrFirstLogIndex = (currentPageNumber * maxRows) - 1;
  }
  SimpleQuery sq = conversionService.convert(request, SimpleQuery.class);
  SolrQuery nextPageLogTimeQuery = new DefaultQueryParser().doConstructSolrQuery(sq);
  nextPageLogTimeQuery.remove("start");
  nextPageLogTimeQuery.remove("rows");
  nextPageLogTimeQuery.setStart(lastOrFirstLogIndex);
  nextPageLogTimeQuery.setRows(1);

  QueryResponse queryResponse = serviceLogsSolrDao.process(nextPageLogTimeQuery);
  if (queryResponse == null) {
    throw new MalformedInputException(String.format("Cannot process next page query for \"%s\" ", keyword));
  }
  SolrDocumentList docList = queryResponse.getResults();
  if (docList == null || docList.isEmpty()) {
    throw new MalformedInputException(String.format("Next page element for \"%s\" is not found", keyword));
  }

  SolrDocument solrDoc = docList.get(0);
  return (Date) solrDoc.get(LOGTIME);
}
 
Example 18
Source File: SolrRrdBackendFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
SolrRrdBackend.SyncData getData(String path) throws IOException {
  if (!persistent) {
    return null;
  }
  try {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add(CommonParams.Q, "{!term f=id}" + ID_PREFIX + ID_SEP + path);
    params.add(CommonParams.FQ, CommonParams.TYPE + ":" + DOC_TYPE);
    QueryResponse rsp = solrClient.query(collection, params);
    SolrDocumentList docs = rsp.getResults();
    if (docs == null || docs.isEmpty()) {
      return null;
    }
    if (docs.size() > 1) {
      throw new SolrServerException("Expected at most 1 doc with id '" + path + "' but got " + docs);
    }
    SolrDocument doc = docs.get(0);
    Object o = doc.getFieldValue(DATA_FIELD);
    if (o == null) {
      return null;
    }
    if (o instanceof byte[]) {
      Object timeObj = doc.getFieldValue("timestamp_l");
      Long time = timeObj instanceof Number ? ((Number)timeObj).longValue() : Long.parseLong(String.valueOf(timeObj));
      return new SolrRrdBackend.SyncData((byte[])o, time);
    } else {
      throw new SolrServerException("Unexpected value of '" + DATA_FIELD + "' field: " + o.getClass().getName() + ": " + o);
    }
  } catch (SolrServerException e) {
    throw new IOException(e);
  }
}
 
Example 19
Source File: RootFieldTest.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Test
public void testLegacyBlockProcessing() throws Exception
{
  SolrClient client = getSolrClient();
  client.deleteByQuery("*:*");// delete everything!

  // Add child free doc
  SolrInputDocument docToUpdate = new SolrInputDocument();
  String docId = "11";
  docToUpdate.addField( "id", docId);
  docToUpdate.addField( "name", "child free doc" );
  client.add(docToUpdate);
  client.commit();

  SolrQuery query = new SolrQuery();
  query.setQuery( "*:*" );
  query.set( CommonParams.FL, "id,name,_root_" );

  SolrDocumentList results = client.query(query).getResults();
  assertThat(results.getNumFound(), is(1L));
  SolrDocument foundDoc = results.get( 0 );

  // Check retrieved field values
  assertThat(foundDoc.getFieldValue( "id" ), is(docId));
  assertThat(foundDoc.getFieldValue( "name" ), is("child free doc"));

  String expectedRootValue = expectRoot() ? docId : null;
  assertThat(MESSAGE, foundDoc.getFieldValue( "_root_" ), is(expectedRootValue));

  // Update the doc
  docToUpdate.setField( "name", "updated doc" );
  client.add(docToUpdate);
  client.commit();

  results = client.query(query).getResults();
  assertEquals( 1, results.getNumFound() );
  foundDoc = results.get( 0 );

  // Check updated field values
  assertThat(foundDoc.getFieldValue( "id" ), is(docId));
  assertThat(foundDoc.getFieldValue( "name" ), is("updated doc"));
  assertThat(MESSAGE, foundDoc.getFieldValue( "_root_" ), is(expectedRootValue));
}
 
Example 20
Source File: TestSubQueryTransformer.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testJustJohnJavabin() throws Exception {
  final SolrQueryRequest johnTwoFL = req(johnAndNancyParams);
  ModifiableSolrParams params = new ModifiableSolrParams(johnTwoFL.getParams());
  params.set("q","name_s:john");
  params.set("wt","javabin");
  
  johnTwoFL.setParams(params);
  
  final NamedList<Object> unmarshalled;
  SolrCore core = johnTwoFL.getCore();
  SolrQueryResponse rsp = new SolrQueryResponse();
  SolrRequestInfo.setRequestInfo(new SolrRequestInfo(johnTwoFL, rsp));

  SolrQueryResponse response = h.queryAndResponse(
      johnTwoFL.getParams().get(CommonParams.QT), johnTwoFL);

  BinaryQueryResponseWriter responseWriter = (BinaryQueryResponseWriter) core.getQueryResponseWriter(johnTwoFL);
  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  responseWriter.write(bytes, johnTwoFL, response);

  try (JavaBinCodec jbc = new JavaBinCodec()) {
    unmarshalled = (NamedList<Object>) jbc.unmarshal(
        new ByteArrayInputStream(bytes.toByteArray()));
  }

  johnTwoFL.close();
  SolrRequestInfo.clearRequestInfo();
  
  SolrDocumentList resultDocs = (SolrDocumentList)(unmarshalled.get("response"));
  
    Map<String,String> engText = new HashMap<>();
    engText.put("text_t", "These guys develop stuff");
    
    Map<String,String> engId = new HashMap<>();
    engId.put("text_t", "These guys develop stuff");
    engId.put("dept_id_s_dv", "Engineering");
    
    for (int docNum : new int []{0, peopleMultiplier-1}) {
      SolrDocument employeeDoc = resultDocs.get(docNum);
      assertEquals("john", employeeDoc.getFieldValue("name_s_dv"));
      for (String subResult : new String []{"depts", "depts_i"}) {

        SolrDocumentList subDoc = (SolrDocumentList)employeeDoc.getFieldValue(subResult);
        for (int deptNum : new int []{0, deptMultiplier-1}) {
          SolrDocument deptDoc = subDoc.get(deptNum);
          Object expectedDept = (subResult.equals("depts") ? engText : engId);
          assertTrue( "" + expectedDept + " equals to " + deptDoc,
              expectedDept.equals(deptDoc));
        }
    }
  }
}