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

The following examples show how to use org.apache.solr.common.SolrDocument#addField() . 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: TestJavaBinCodec.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public static SolrDocument generateSolrDocumentWithChildDocs() {
  SolrDocument parentDocument = new SolrDocument();
  parentDocument.addField("id", "1");
  parentDocument.addField("subject", "parentDocument");

  SolrDocument childDocument = new SolrDocument();
  childDocument.addField("id", "2");
  childDocument.addField("cat", "foo");

  SolrDocument secondKid = new SolrDocument();
  secondKid.addField("id", "22");
  secondKid.addField("cat", "bar");

  SolrDocument grandChildDocument = new SolrDocument();
  grandChildDocument.addField("id", "3");

  childDocument.addChildDocument(grandChildDocument);
  parentDocument.addChildDocument(childDocument);
  parentDocument.addChildDocument(secondKid);

  return parentDocument;
}
 
Example 2
Source File: SecureRealTimeGetComponent.java    From incubator-sentry with Apache License 2.0 6 votes vote down vote up
private static SolrDocument toSolrDoc(Document doc, IndexSchema schema) {
  SolrDocument out = new SolrDocument();
  for ( IndexableField f : doc.getFields() ) {
    // Make sure multivalued fields are represented as lists
    Object existing = out.get(f.name());
    if (existing == null) {
      SchemaField sf = schema.getFieldOrNull(f.name());

      // don't return copyField targets
      if (sf != null && schema.isCopyFieldTarget(sf)) continue;

      if (sf != null && sf.multiValued()) {
        List<Object> vals = new ArrayList<>();
        vals.add( f );
        out.setField( f.name(), vals );
      }
      else{
        out.setField( f.name(), f );
      }
    }
    else {
      out.addField( f.name(), f );
    }
  }
  return out;
}
 
Example 3
Source File: SolrUtilitiesTest.java    From metron with Apache License 2.0 6 votes vote down vote up
@Test
public void toDocumentShouldProperlyReturnDocument() throws Exception {
  long expectedTimestamp = System.currentTimeMillis();
  SolrDocument solrDocument = new SolrDocument();
  solrDocument.addField(SolrDao.VERSION_FIELD, 1.0);
  solrDocument.addField(Constants.GUID, "guid");
  solrDocument.addField(Constants.SENSOR_TYPE, "bro");
  solrDocument.addField(Constants.Fields.TIMESTAMP.getName(), expectedTimestamp);
  solrDocument.addField("field", "value");

  Document expectedDocument = new Document(new HashMap<String, Object>() {{
    put("field", "value");
    put(Constants.GUID, "guid");
    put(Constants.SENSOR_TYPE, "bro");
    put(Constants.Fields.TIMESTAMP.getName(), expectedTimestamp);
  }}, "guid", "bro", expectedTimestamp);

  Document actualDocument = SolrUtilities.toDocument(solrDocument);
  assertEquals(expectedDocument, actualDocument);
}
 
Example 4
Source File: SolrClientInterceptorTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
private NamedList<Object> getGetResponse() {
    NamedList<Object> response = new NamedList<Object>();
    response.add("responseHeader", header);
    SolrDocumentList list = new SolrDocumentList();
    list.setStart(0);
    list.setNumFound(1);
    list.setMaxScore(.0f);

    SolrDocument doc = new SolrDocument();
    doc.addField("id", 1);
    doc.addField("_version", 1634676349644832768L);
    list.add(doc);

    response.add("response", list);
    return response;
}
 
Example 5
Source File: SolrClientInterceptorTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
private NamedList<Object> getQueryResponse() {
    NamedList<Object> response = new NamedList<Object>();
    response.add("responseHeader", header);
    SolrDocumentList list = new SolrDocumentList();
    list.setStart(0);
    list.setNumFound(100);
    list.setMaxScore(.0f);

    for (int start = 0; start < 10; start++) {
        SolrDocument doc = new SolrDocument();
        doc.addField("id", start);
        doc.addField("_version", 1634676349644832768L);
        list.add(doc);
    }
    response.add("response", list);
    return response;
}
 
Example 6
Source File: MockSolrEntityProcessor.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private SolrDocumentList getDocs(int start, int rows) {
  SolrDocumentList docs = new SolrDocumentList();
  docs.setNumFound(docsData.size());
  docs.setStart(start);

  int endIndex = start + rows;
  int end = docsData.size() < endIndex ? docsData.size() : endIndex;
  for (int i = start; i < end; i++) {
    SolrDocument doc = new SolrDocument();
    SolrTestCaseJ4.Doc testDoc = docsData.get(i);
    doc.addField("id", testDoc.id);
    doc.addField("description", testDoc.getValues("description"));
    docs.add(doc);
  }
  return docs;
}
 
Example 7
Source File: AlfrescoSearchHandler.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
public final SolrDocument toSolrDocument(Document doc, IndexSchema schema) {
	SolrDocument out = new SolrDocument();
	for (IndexableField f : doc) {
		// Make sure multivalued fields are represented as lists
		Object existing = out.get(f.name());
		if (existing == null) {
			SchemaField sf = schema.getFieldOrNull(f.name());
			if (sf != null && sf.multiValued()) {
				List<Object> vals = new ArrayList<>();
				vals.add(f);
				out.setField(f.name(), vals);
			} else {
				out.setField(f.name(), f);
			}
		} else {
			out.addField(f.name(), f);
		}
	}
	return out;
}
 
Example 8
Source File: GeoTransformerFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
void addShape(SolrDocument doc, Shape shape) {
  if(isJSON) {
    doc.addField(display, new WriteableGeoJSON(shape, writer));
  }
  else {
    doc.addField(display, writer.toString(shape));
  }
}
 
Example 9
Source File: RealTimeGetComponent.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static SolrDocument toSolrDoc(Document doc, IndexSchema schema) {
  SolrDocument out = new SolrDocument();
  for( IndexableField f : doc.getFields() ) {
    // Make sure multivalued fields are represented as lists
    Object existing = out.get(f.name());
    if (existing == null) {
    SchemaField sf = schema.getFieldOrNull(f.name());

    // don't return copyField targets
      if (sf != null && schema.isCopyFieldTarget(sf)) continue;
    
      if (sf != null && sf.multiValued()) {
      List<Object> vals = new ArrayList<>();
        if (f.fieldType().docValuesType() == DocValuesType.SORTED_NUMERIC) {
          // SORTED_NUMERICS store sortable bits version of the value, need to retrieve the original
          vals.add(sf.getType().toObject(f)); // (will materialize by side-effect)
        } else {
          vals.add( materialize(f) );
        }
      out.setField(f.name(), vals);
    } else {
        out.setField( f.name(), materialize(f) );
      }
    }
    else {
      out.addField( f.name(), materialize(f) );
    }
  }
  return out;
}
 
Example 10
Source File: TestBinaryResponseWriter.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public void testResolverSolrDocumentPartialFields() throws Exception {
  LocalSolrQueryRequest req = lrf.makeRequest("q", "*:*",
                                              "fl", "id,xxx,ddd_s"); 
  SolrDocument in = new SolrDocument();
  in.addField("id", 345);
  in.addField("aaa_s", "aaa");
  in.addField("bbb_s", "bbb");
  in.addField("ccc_s", "ccc");
  in.addField("ddd_s", "ddd");
  in.addField("eee_s", "eee");    

  Resolver r = new Resolver(req, new SolrReturnFields(req));
  Object o = r.resolve(in, new JavaBinCodec());

  assertNotNull("obj is null", o);
  assertTrue("obj is not doc", o instanceof SolrDocument);

  SolrDocument out = new SolrDocument();
  for (Map.Entry<String, Object> e : in) {
    if(r.isWritable(e.getKey())) out.put(e.getKey(),e.getValue());

  }
  assertTrue("id not found", out.getFieldNames().contains("id"));
  assertTrue("ddd_s not found", out.getFieldNames().contains("ddd_s"));
  assertEquals("Wrong number of fields found", 
               2, out.getFieldNames().size());
  req.close();

}
 
Example 11
Source File: TestCloudInspectUtil.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private SolrDocumentList getDocList(String ... ids) {
  SolrDocumentList list = new SolrDocumentList();
  for (String id : ids) {
    SolrDocument doc = new SolrDocument();
    doc.addField("id", id);
    list.add(doc);
  }
  return list;
}
 
Example 12
Source File: AnalysisHandler.java    From chronix.server with Apache License 2.0 5 votes vote down vote up
private SolrDocument solrDocumentWithOutTimeSeriesFunctionResults(boolean dataShouldReturned, boolean dataAsJson, ChronixTimeSeries timeSeries) {
    SolrDocument doc = new SolrDocument();

    //add the join key
    doc.put(ChronixQueryParams.JOIN_KEY, timeSeries.getJoinKey());

    for (Map.Entry<String, Object> entry : (Set<Map.Entry<String, Object>>) timeSeries.getAttributes().entrySet()) {
        doc.addField(entry.getKey(), entry.getValue());
    }

    //add the metric field as it is not stored in the getAttributes
    doc.addField(Schema.NAME, timeSeries.getName());
    doc.addField(Schema.TYPE, timeSeries.getType());

    if (dataShouldReturned) {
        //ensure that the returned data is sorted
        timeSeries.sort();
        //data should returned serialized as json
        if (dataAsJson) {
            doc.setField(ChronixQueryParams.DATA_AS_JSON, timeSeries.dataAsJson());
        } else {
            doc.addField(Schema.DATA, timeSeries.dataAsBlob());
        }
    }

    //TODO: Fix this. It is expensive to calculate this based on the points.
    // How can we avoid this?
    // Optimization: Transformations should return the first an the last point
    // Aggregations / Analyses does not need to return this.
    doc.addField(Schema.START, timeSeries.getStart());
    doc.addField(Schema.END, timeSeries.getEnd());

    return doc;
}
 
Example 13
Source File: LTRFeatureLoggerTransformerFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void implTransform(SolrDocument doc, int docid, Float score)
    throws IOException {
  Object fv = featureLogger.getFeatureVector(docid, scoringQuery, searcher);
  if (fv == null) { // FV for this document was not in the cache
    fv = featureLogger.makeFeatureVector(
        LTRRescorer.extractFeaturesInfo(
            modelWeight,
            docid,
            (docsWereNotReranked ? score : null),
            leafContexts));
  }

  doc.addField(name, fv);
}
 
Example 14
Source File: SolrSearchDaoTest.java    From metron with Apache License 2.0 5 votes vote down vote up
private SolrDocument createSolrDocument(String sensorType, Long timestamp) {
  SolrDocument solrDocument = new SolrDocument();
  solrDocument.addField(SolrDao.VERSION_FIELD, 1.0);
  solrDocument.addField(Constants.GUID, UUID.randomUUID().toString());
  solrDocument.addField(Constants.SENSOR_TYPE, sensorType);
  solrDocument.addField(Constants.Fields.TIMESTAMP.getName(), timestamp);
  solrDocument.addField(Constants.Fields.SRC_ADDR.getName(), "192.168.1.1");
  return solrDocument;
}
 
Example 15
Source File: BlurResultHelper.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
private static SolrDocument convertRecord(FetchRecordResult recResult) {
  SolrDocument doc = new SolrDocument();
  Record record = recResult.getRecord();

  doc.addField(BlurConstants.RECORD_ID, record.getRecordId());

  for (Column col : record.getColumns()) {
    doc.addField(joinColumnFamily(record.getFamily(), col.getName()), col.getValue());
  }

  return doc;
}
 
Example 16
Source File: JSONWriterTest.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Test
public void testJSONSolrDocument() throws Exception {
  SolrQueryRequest req = req(CommonParams.WT,"json",
                             CommonParams.FL,"id,score,_children_,path");
  SolrQueryResponse rsp = new SolrQueryResponse();
  JSONResponseWriter w = new JSONResponseWriter();

  ReturnFields returnFields = new SolrReturnFields(req);
  rsp.setReturnFields(returnFields);

  StringWriter buf = new StringWriter();

  SolrDocument childDoc = new SolrDocument();
  childDoc.addField("id", "2");
  childDoc.addField("score", "0.4");
  childDoc.addField("path", Arrays.asList("a>b", "a>b>c"));

  SolrDocumentList childList = new SolrDocumentList();
  childList.setNumFound(1);
  childList.setStart(0);
  childList.add(childDoc);

  SolrDocument solrDoc = new SolrDocument();
  solrDoc.addField("id", "1");
  solrDoc.addField("subject", "hello2");
  solrDoc.addField("title", "hello3");
  solrDoc.addField("score", "0.7");
  solrDoc.setField("_children_", childList);

  SolrDocumentList list = new SolrDocumentList();
  list.setNumFound(1);
  list.setStart(0);
  list.setMaxScore(0.7f);
  list.add(solrDoc);

  rsp.addResponse(list);

  w.write(buf, req, rsp);
  String result = buf.toString();
  assertFalse("response contains unexpected fields: " + result, 
              result.contains("hello") || 
              result.contains("\"subject\"") || 
              result.contains("\"title\""));
  assertTrue("response doesn't contain expected fields: " + result, 
             result.contains("\"id\"") &&
             result.contains("\"score\"") && result.contains("_children_"));

  String expectedResult = "{'response':{'numFound':1,'start':0,'maxScore':0.7, 'numFoundExact':true,'docs':[{'id':'1', 'score':'0.7'," +
      " '_children_':{'numFound':1,'start':0,'numFoundExact':true,'docs':[{'id':'2', 'score':'0.4', 'path':['a>b', 'a>b>c']}] }}] }}";
  String error = JSONTestUtil.match(result, "=="+expectedResult);
  assertNull("response validation failed with error: " + error, error);

  req.close();
}
 
Example 17
Source File: TestJavaBinCodec.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"unchecked"})
private List<Object> generateAllDataTypes() {
  List<Object> types = new ArrayList<>();

  types.add(null); //NULL
  types.add(true);
  types.add(false);
  types.add((byte) 1);
  types.add((short) 2);
  types.add((double) 3);

  types.add(-4);
  types.add(4);
  types.add(42);

  types.add((long) -5);
  types.add((long) 5);
  types.add((long) 50);

  types.add((float) 6);
  types.add(new Date(0));

  Map<Integer, Integer> map = new HashMap<>();
  map.put(1, 2);
  types.add(map);

  SolrDocument doc = new SolrDocument();
  doc.addField("foo", "bar");
  types.add(doc);

  SolrDocumentList solrDocs = new SolrDocumentList();
  solrDocs.setMaxScore(1.0f);
  solrDocs.setNumFound(1);
  solrDocs.setNumFoundExact(Boolean.TRUE);
  solrDocs.setStart(0);
  solrDocs.add(0, doc);
  types.add(solrDocs);

  types.add(new byte[] {1,2,3,4,5});

  // TODO?
  // List<String> list = new ArrayList<String>();
  // list.add("one");
  // types.add(list.iterator());

  types.add((byte) 15); //END

  SolrInputDocument idoc = new SolrInputDocument();
  idoc.addField("foo", "bar");
  types.add(idoc);

  SolrInputDocument parentDoc = new SolrInputDocument();
  parentDoc.addField("foo", "bar");
  SolrInputDocument childDoc = new SolrInputDocument();
  childDoc.addField("foo", "bar");
  parentDoc.addChildDocument(childDoc);
  types.add(parentDoc);

  types.add(new EnumFieldValue(1, "foo"));

  types.add(map.entrySet().iterator().next()); //Map.Entry

  types.add((byte) (1 << 5)); //TAG_AND_LEN

  types.add("foo");
  types.add(1);
  types.add((long) 2);

  @SuppressWarnings({"rawtypes"})
  SimpleOrderedMap simpleOrderedMap = new SimpleOrderedMap();
  simpleOrderedMap.add("bar", "barbar");
  types.add(simpleOrderedMap);

  NamedList<String> nl = new NamedList<>();
  nl.add("foo", "barbar");
  types.add(nl);

  return types;
}