Java Code Examples for org.apache.solr.common.SolrDocument#getChildDocuments()

The following examples show how to use org.apache.solr.common.SolrDocument#getChildDocuments() . 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: SolrController.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/getById/{id}")
    public String getByIdFromSolr(@PathVariable("id") String id) throws IOException, SolrServerException {

        //根据id查询内容
        SolrDocument solrDocument = solrClient.getById(id);
        //获取filedName
        Collection<String> fieldNames = solrDocument.getFieldNames();
        //获取file名和内容
        Map<String, Object> fieldValueMap = solrDocument.getFieldValueMap();

//            int childDocumentCount = solrDocument.getChildDocumentCount();

        List<SolrDocument> childDocuments = solrDocument.getChildDocuments();
        String results = solrDocument.toString();
        //fieldNames
        // fieldValueMap
        // childDocuments;
        return results;

    }
 
Example 2
Source File: SolrUtils.java    From vind with Apache License 2.0 6 votes vote down vote up
public static SolrInputDocument toSolrInputDocument(SolrDocument solrDocument) {
    SolrInputDocument solrInputDocument = new SolrInputDocument();

    for (String name : solrDocument.getFieldNames()) {
        solrInputDocument.addField(name, solrDocument.getFieldValue(name));
    }

    //Don't forget children documents
    if(solrDocument.getChildDocuments() != null) {
        for(SolrDocument childDocument : solrDocument.getChildDocuments()) {
            //You can add paranoic check against infinite loop childDocument == solrDocument
            solrInputDocument.addChildDocument(toSolrInputDocument(childDocument));
        }
    }
    return solrInputDocument;
}
 
Example 3
Source File: SolrUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Converts a {@link SolrDocument} to a {@link SolrInputDocument}
 *
 * @param solrDocument
 * @return input document
 */
public static SolrInputDocument toSolrInputDocument(SolrDocument solrDocument) {

	/*
	 * Note: ClientUtils.toSolrInputDocument was removed in solr 6 Replacement found on
	 * https://stackoverflow.com/questions/38266684/
	 * substitute-of-org-apache-solr-client-solrj-util-clientutils-tosolrinputdocument
	 */

	SolrInputDocument solrInputDocument = new SolrInputDocument();

	for (String name : solrDocument.getFieldNames()) {
		solrInputDocument.addField(name, solrDocument.getFieldValue(name));
	}

	// Don't forget children documents
	if (solrDocument.getChildDocuments() != null) {
		for (SolrDocument childDocument : solrDocument.getChildDocuments()) {
			// You can add paranoic check against infinite loop childDocument == solrDocument
			solrInputDocument.addChildDocument(toSolrInputDocument(childDocument));
		}
	}
	return solrInputDocument;
}
 
Example 4
Source File: SolrUtilities.java    From metron with Apache License 2.0 6 votes vote down vote up
protected static void insertChildAlerts(SolrDocument solrDocument, Map<String, Object> document) {
  // Make sure to put child alerts in
  if (solrDocument.hasChildDocuments() && solrDocument
      .getFieldValue(Constants.SENSOR_TYPE)
      .equals(MetaAlertConstants.METAALERT_TYPE)) {
    List<Map<String, Object>> childDocuments = new ArrayList<>();
    for (SolrDocument childDoc : solrDocument.getChildDocuments()) {
      Map<String, Object> childDocMap = new HashMap<>();
      childDoc.getFieldNames().stream()
          .filter(name -> !name.equals(SolrDao.VERSION_FIELD))
          .forEach(name -> childDocMap.put(name, childDoc.getFieldValue(name)));
      childDocuments.add(childDocMap);
    }

    document.put(MetaAlertConstants.ALERT_FIELD, childDocuments);
  }
}
 
Example 5
Source File: SolrControllerTest.java    From Spring-Boot-Book with Apache License 2.0 5 votes vote down vote up
@Test
public void getByIdFromSolr() throws IOException, SolrServerException {
    //根据id查询内容
    String id="8888888";
    SolrDocument solrDocument = solrClient.getById(id);
    //获取filedName
    Collection<String> fieldNames = solrDocument.getFieldNames();
    //获取file名和内容
    Map<String, Object> fieldValueMap = solrDocument.getFieldValueMap();
    List<SolrDocument> childDocuments = solrDocument.getChildDocuments();
    String results = solrDocument.toString();
    System.out.println(results);

}
 
Example 6
Source File: JavaBinCodec.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void writeSolrDocument(SolrDocument doc) throws IOException {
  List<SolrDocument> children = doc.getChildDocuments();
  int fieldsCount = 0;
  if(writableDocFields == null || writableDocFields.wantsAllFields() || ignoreWritable){
    fieldsCount = doc.size();
  } else {
    for (Entry<String, Object> e : doc) {
      if(toWrite(e.getKey())) fieldsCount++;
    }
  }
  int sz = fieldsCount + (children==null ? 0 : children.size());
  writeTag(SOLRDOC);
  writeTag(ORDERED_MAP, sz);
  if (cew == null) cew = new ConditionalKeyMapWriter.EntryWriterWrapper(ew, (k) -> toWrite(k.toString()));
  doc.writeMap(cew);
  if (children != null) {
    try {
      ignoreWritable = true;
      for (SolrDocument child : children) {
        writeSolrDocument(child);
      }
    } finally {
      ignoreWritable = false;
    }
  }

}
 
Example 7
Source File: TestJavaBinCodec.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseChildDocuments() throws IOException {
  SolrDocument result = (SolrDocument) serializeAndDeserialize(generateSolrDocumentWithChildDocs());
  assertEquals(2, result.size());
  assertEquals("1", result.getFieldValue("id"));
  assertEquals("parentDocument", result.getFieldValue("subject"));
  assertTrue(result.hasChildDocuments());

  List<SolrDocument> childDocuments = result.getChildDocuments();
  assertNotNull(childDocuments);
  assertEquals(2, childDocuments.size());
  assertEquals(2, childDocuments.get(0).size());
  assertEquals("2", childDocuments.get(0).getFieldValue("id"));
  assertEquals("foo", childDocuments.get(0).getFieldValue("cat"));

  assertEquals(2, childDocuments.get(1).size());
  assertEquals("22", childDocuments.get(1).getFieldValue("id"));
  assertEquals("bar", childDocuments.get(1).getFieldValue("cat"));
  assertFalse(childDocuments.get(1).hasChildDocuments());
  assertNull(childDocuments.get(1).getChildDocuments());

  assertTrue(childDocuments.get(0).hasChildDocuments());
  List<SolrDocument> grandChildDocuments = childDocuments.get(0).getChildDocuments();
  assertNotNull(grandChildDocuments);
  assertEquals(1, grandChildDocuments.size());
  assertEquals(1, grandChildDocuments.get(0).size());
  assertEquals("3", grandChildDocuments.get(0).getFieldValue("id"));
  assertFalse(grandChildDocuments.get(0).hasChildDocuments());
  assertNull(grandChildDocuments.get(0).getChildDocuments());
}
 
Example 8
Source File: XMLWriter.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * The SolrDocument should already have multivalued fields implemented as
 * Collections -- this will not rewrite to &lt;arr&gt;
 */
@Override
public void writeSolrDocument(String name, SolrDocument doc, ReturnFields returnFields, int idx ) throws IOException {
  startTag("doc", name, false);
  incLevel();

  for (String fname : doc.getFieldNames()) {
    if (returnFields!= null && !returnFields.wantsField(fname)) {
      continue;
    }

    Object val = doc.getFieldValue(fname);
    if( "_explain_".equals( fname ) ) {
      if (log.isDebugEnabled()) {
        log.debug(String.valueOf(val));
      }
    }
    writeVal(fname, val);
  }

  if(doc.hasChildDocuments()) {
    for(SolrDocument childDoc : doc.getChildDocuments()) {
      writeSolrDocument(null, childDoc, new SolrReturnFields(), idx);
    }
  }

  decLevel();
  writer.write("</doc>");
}
 
Example 9
Source File: TestChildDocTransformer.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void testChildReturnFields() throws Exception {

    assertJQ(req("q", "*:*", "fq", "subject:\"parentDocument\" ",
        "fl", "*,[child parentFilter=\"subject:parentDocument\" fl=\"intDvoDefault,child_fl:[value v='child_fl_test']\"]"),
        "/response/docs/[0]/intDefault==42",
        "/response/docs/[0]/_childDocuments_/[0]/intDvoDefault==42",
        "/response/docs/[0]/_childDocuments_/[0]/child_fl=='child_fl_test'");

    try(SolrQueryRequest req = req("q", "*:*", "fq", "subject:\"parentDocument\" ",
        "fl", "intDefault,[child parentFilter=\"subject:parentDocument\" fl=\"intDvoDefault, [docid]\"]")) {
      BasicResultContext res = (BasicResultContext) h.queryAndResponse("/select", req).getResponse();
      Iterator<SolrDocument> docsStreamer = res.getProcessedDocuments();
      while (docsStreamer.hasNext()) {
        SolrDocument doc = docsStreamer.next();
        assertFalse("root docs should not contain fields specified in child return fields", doc.containsKey("intDvoDefault"));
        assertTrue("root docs should contain fields specified in query return fields", doc.containsKey("intDefault"));
        Collection<SolrDocument> childDocs = doc.getChildDocuments();
        for(SolrDocument childDoc: childDocs) {
          assertEquals("child doc should only have 2 keys", 2, childDoc.keySet().size());
          assertTrue("child docs should contain fields specified in child return fields", childDoc.containsKey("intDvoDefault"));
          assertEquals("child docs should contain fields specified in child return fields",
              42, childDoc.getFieldValue("intDvoDefault"));
          assertTrue("child docs should contain fields specified in child return fields", childDoc.containsKey("[docid]"));
        }
      }
    }
  }
 
Example 10
Source File: SolrBoltActionTest.java    From storm-solr with Apache License 2.0 5 votes vote down vote up
protected void doNestedDocTest() throws Exception {
  SolrBoltAction sba = new SolrBoltAction(cloudSolrClient);
  sba.setSolrInputDocumentMapper(new NestedDocumentMapper());
  sba.setUpdateRequestStrategy(new DefaultUpdateRequestStrategy());
  sba.setMaxBufferSize(1); // to avoid buffering docs

  String docId = "1";

  JSONArray jsonDocs = NestedDocumentMapperTest.loadNestedDocs();
  Tuple mockTuple = mock(Tuple.class);
  when(mockTuple.size()).thenReturn(2);
  when(mockTuple.getString(0)).thenReturn(docId);
  when(mockTuple.getValue(1)).thenReturn(jsonDocs.get(0));

  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);
  query.set("fl", "*,[child parentFilter=id:"+docId+" limit=100]");
  QueryResponse qr = cloudSolrClient.query(query);
  SolrDocumentList results = qr.getResults();
  assertTrue(results.getNumFound() == 1);
  SolrDocument doc = results.get(0);
  assertNotNull(doc);

  System.out.println("\n\n>> doc: "+doc+"\n\n");
  if (doc.hasChildDocuments()) {
    for (SolrDocument child : doc.getChildDocuments()) {
      System.out.println("\n>> "+child+"\n");
    }
  } else {
    System.out.println("no child documents returned");
  }

}
 
Example 11
Source File: SolrTestCaseJ4.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public boolean compareSolrDocument(Object expected, Object actual) {

    if (!(expected instanceof SolrDocument)  || !(actual instanceof SolrDocument)) {
      return false;
    }

    if (expected == actual) {
      return true;
    }

    SolrDocument solrDocument1 = (SolrDocument) expected;
    SolrDocument solrDocument2 = (SolrDocument) actual;

    if(solrDocument1.getFieldNames().size() != solrDocument2.getFieldNames().size()) {
      return false;
    }

    Iterator<String> iter1 = solrDocument1.getFieldNames().iterator();
    Iterator<String> iter2 = solrDocument2.getFieldNames().iterator();

    if(iter1.hasNext()) {
      String key1 = iter1.next();
      String key2 = iter2.next();

      Object val1 = solrDocument1.getFieldValues(key1);
      Object val2 = solrDocument2.getFieldValues(key2);

      if(!key1.equals(key2) || !val1.equals(val2)) {
        return false;
      }
    }

    if(solrDocument1.getChildDocuments() == null && solrDocument2.getChildDocuments() == null) {
      return true;
    }
    if(solrDocument1.getChildDocuments() == null || solrDocument2.getChildDocuments() == null) {
      return false;
    } else if(solrDocument1.getChildDocuments().size() != solrDocument2.getChildDocuments().size()) {
      return false;
    } else {
      Iterator<SolrDocument> childDocsIter1 = solrDocument1.getChildDocuments().iterator();
      Iterator<SolrDocument> childDocsIter2 = solrDocument2.getChildDocuments().iterator();
      while(childDocsIter1.hasNext()) {
        if(!compareSolrDocument(childDocsIter1.next(), childDocsIter2.next())) {
          return false;
        }
      }
      return true;
    }
  }
 
Example 12
Source File: JSONWriter.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public void writeSolrDocument(String name, SolrDocument doc, ReturnFields returnFields, int idx) throws IOException {
  if( idx > 0 ) {
    writeArraySeparator();
  }

  indent();
  writeMapOpener(doc.size());
  incLevel();

  boolean first=true;
  for (String fname : doc.getFieldNames()) {
    if (returnFields!= null && !returnFields.wantsField(fname)) {
      continue;
    }

    if (first) {
      first=false;
    }
    else {
      writeMapSeparator();
    }

    indent();
    writeKey(fname, true);
    Object val = doc.getFieldValue(fname);
    writeVal(fname, val);
  }

  if(doc.hasChildDocuments()) {
    if(first == false) {
      writeMapSeparator();
      indent();
    }
    writeKey("_childDocuments_", true);
    writeArrayOpener(doc.getChildDocumentCount());
    List<SolrDocument> childDocs = doc.getChildDocuments();
    for(int i=0; i<childDocs.size(); i++) {
      writeSolrDocument(null, childDocs.get(i), null, i);
    }
    writeArrayCloser();
  }

  decLevel();
  writeMapCloser();
}
 
Example 13
Source File: GeoJSONResponseWriter.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public void writeSolrDocument(String name, SolrDocument doc, ReturnFields returnFields, int idx) throws IOException {
  if( idx > 0 ) {
    writeArraySeparator();
  }

  indent();
  writeMapOpener(-1); 
  incLevel();

  writeKey("type", false);
  writeVal(null, "Feature");
  
  Object val = doc.getFieldValue(geofield);
  if(val != null) {  
    writeFeatureGeometry(val);
  }
  
  boolean first=true;
  for (String fname : doc.getFieldNames()) {
    if (fname.equals(geofield) || ((returnFields!= null && !returnFields.wantsField(fname)))) {
      continue;
    }
    writeMapSeparator();
    if (first) {
      indent();
      writeKey("properties", false);
      writeMapOpener(-1); 
      incLevel();
      
      first=false;
    }

    indent();
    writeKey(fname, true);
    val = doc.getFieldValue(fname);
    writeVal(fname, val);
  }

  // GeoJSON does not really support nested FeatureCollections
  if(doc.hasChildDocuments()) {
    if(first == false) {
      writeMapSeparator();
      indent();
    }
    writeKey("_childDocuments_", true);
    writeArrayOpener(doc.getChildDocumentCount());
    List<SolrDocument> childDocs = doc.getChildDocuments();
    for(int i=0; i<childDocs.size(); i++) {
      writeSolrDocument(null, childDocs.get(i), null, i);
    }
    writeArrayCloser();
  }

  // check that we added any properties
  if(!first) {
    decLevel();
    writeMapCloser();
  }
  
  decLevel();
  writeMapCloser();
}