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

The following examples show how to use org.apache.solr.common.SolrDocument#setField() . 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: 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 2
Source File: JavaBinCodec.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public SolrDocument readSolrDocument(DataInputInputStream dis) throws IOException {
  tagByte = dis.readByte();
  int size = readSize(dis);
  SolrDocument doc = new SolrDocument(new LinkedHashMap<>(size));
  for (int i = 0; i < size; i++) {
    String fieldName;
    Object obj = readVal(dis); // could be a field name, or a child document
    if (obj instanceof SolrDocument) {
      doc.addChildDocument((SolrDocument)obj);
      continue;
    } else {
      fieldName = (String)obj;
    }
    Object fieldVal = readVal(dis);
    doc.setField(fieldName, fieldVal);
  }
  return doc;
}
 
Example 3
Source File: TestChildDocTransformerHierarchy.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked"})
private static void cleanSolrDocumentFields(SolrDocument input) {
  for(String fieldName: fieldsToRemove) {
    input.removeFields(fieldName);
  }
  for(Map.Entry<String, Object> field: input) {
    Object val = field.getValue();
    if(val instanceof Collection) {
      Object newVals = ((Collection) val).stream().map((item) -> (cleanIndexableField(item)))
          .collect(Collectors.toList());
      input.setField(field.getKey(), newVals);
      continue;
    }
    input.setField(field.getKey(), cleanIndexableField(field.getValue()));
  }
}
 
Example 4
Source File: SubQueryAugmenterFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void transform(SolrDocument doc, int docid) {

  final SolrParams docWithDeprefixed = SolrParams.wrapDefaults(
      new DocRowParams(doc, prefix, separator), baseSubParams);
  try {
    QueryResponse rsp = server.query(coreName, docWithDeprefixed);
    SolrDocumentList docList = rsp.getResults();
    doc.setField(getName(), new Result(docList));
  } catch (Exception e) {
    String docString = doc.toString();
    throw new SolrException(ErrorCode.BAD_REQUEST, "while invoking " +
        name + ":[subquery"+ (coreName!=null ? "fromIndex="+coreName : "") +"] on doc=" +
          docString.substring(0, Math.min(100, docString.length())), e.getCause());
  }
}
 
Example 5
Source File: GeoTransformerFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
void addValue(SolrDocument doc, Object val) {
  if(val == null) {
    return;
  }
  
  if(val instanceof Shape) {
    addShape(doc, (Shape)val);
  }
  // Don't explode on 'InvalidShpae'
  else if( val instanceof Exception) {
    doc.setField( display_error, ((Exception)val).toString() );
  }
  else {
    // Use the stored value
    if(val instanceof IndexableField) {
      val = ((IndexableField)val).stringValue();
    }
    try {
      addShape(doc, formats.read(val.toString()));
    }
    catch(Exception ex) {
      doc.setField( display_error, ex.toString() );
    }
  }
}
 
Example 6
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 7
Source File: ChildDocTransformer.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private static void addChildrenToParent(SolrDocument parent, Collection<SolrDocument> children, String cDocsPath) {
  // if no paths; we do not need to add the child document's relation to its parent document.
  if (cDocsPath.equals(ANON_CHILD_KEY)) {
    parent.addChildDocuments(children);
    return;
  }
  // lookup leaf key for these children using path
  // depending on the label, add to the parent at the right key/label
  String trimmedPath = trimLastPound(cDocsPath);
  // if the child doc's path does not end with #, it is an array(same string is returned by ChildDocTransformer#trimLastPound)
  if (!parent.containsKey(trimmedPath) && (trimmedPath == cDocsPath)) {
    List<SolrDocument> list = new ArrayList<>(children);
    parent.setField(trimmedPath, list);
    return;
  }
  // is single value
  parent.setField(trimmedPath, ((List)children).get(0));
}
 
Example 8
Source File: RawValueTransformerFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void transform(SolrDocument doc, int docid) {
  Object val = doc.remove(field);
  if(val==null) {
    return;
  }
  if(val instanceof Collection) {
    @SuppressWarnings({"rawtypes"})
    Collection current = (Collection)val;
    ArrayList<WriteableStringValue> vals = new ArrayList<RawValueTransformerFactory.WriteableStringValue>();
    for(Object v : current) {
      vals.add(new WriteableStringValue(v));
    }
    doc.setField(display, vals);
  }
  else {
    doc.setField(display, new WriteableStringValue(val));
  }
}
 
Example 9
Source File: ConverterService.java    From chronix.server with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a lucene document to a solr document.
 *
 * @param schema    the index schema
 * @param luceneDoc the lucene document
 * @return solr document
 */
public SolrDocument toSolrDoc(IndexSchema schema, Document luceneDoc) {
    SolrDocument solrDoc = new SolrDocument();
    luceneDoc.forEach(it -> solrDoc.addField(it.name(), schema.getField(it.name()).getType().toObject(it)));
    for (String field : solrDoc.getFieldNames()) {
        Object value = solrDoc.getFieldValue(field);
        if (value instanceof ByteBuffer) {
            solrDoc.setField(field, ((ByteBuffer) value).array());
        }
    }
    return solrDoc;
}
 
Example 10
Source File: TestDocumentObjectBinder.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static SolrDocument toSolrDocument(SolrInputDocument d) {
  SolrDocument doc = new SolrDocument();
  for (SolrInputField field : d) {
    doc.setField(field.getName(), field.getValue());
  }
  if (d.getChildDocuments() != null) {
    for (SolrInputDocument in : d.getChildDocuments()) {
      doc.addChildDocument(toSolrDocument(in));
    }
  }
  return doc;
}
 
Example 11
Source File: SolrTestCaseJ4.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private static SolrDocument toSolrDoc(SolrInputDocument sid) {
  SolrDocument doc = new SolrDocument();
  for(SolrInputField field: sid) {
    doc.setField(field.getName(), field.getValue());
  }
  return doc;
}
 
Example 12
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 13
Source File: TestCustomDocTransformer.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * This transformer simply concatenates the values of multiple fields
 */
@Override
public void transform(SolrDocument doc, int docid) throws IOException {
  str.setLength(0);
  for(String s : extra) {
    String v = getAsString(s, doc);
    str.append(v).append('#');
  }
  System.out.println( "HELLO: "+str );
  doc.setField(name, str.toString());
}
 
Example 14
Source File: RenameFieldTransformer.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void transform(SolrDocument doc, int docid) {
  Object v = (copy)?doc.get(from) : doc.remove( from );
  if( v != null ) {
    doc.setField(to, v);
  }
}
 
Example 15
Source File: DuplicateDocumentList.java    From BioSolr with Apache License 2.0 5 votes vote down vote up
public void setParentDoc(int index, Object sortValue, float score) {
  SolrDocument parent = new SolrDocument();
  parent.setField(MERGE_PARENT_FIELD, true);
  if (! Float.isNaN(score)) {
    parent.setField("score", score);
  }
  if (sortValue != null) {
    parent.setField(SORT_VALUE_FIELD, sortValue);
  }
  super.set(index, parent);
}
 
Example 16
Source File: QueryComponent.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
protected void returnFields(ResponseBuilder rb, ShardRequest sreq) {
  // Keep in mind that this could also be a shard in a multi-tiered system.
  // TODO: if a multi-tiered system, it seems like some requests
  // could/should bypass middlemen (like retrieving stored fields)
  // TODO: merge fsv to if requested

  if ((sreq.purpose & ShardRequest.PURPOSE_GET_FIELDS) != 0) {
    boolean returnScores = (rb.getFieldFlags() & SolrIndexSearcher.GET_SCORES) != 0;

    String keyFieldName = rb.req.getSchema().getUniqueKeyField().getName();
    boolean removeKeyField = !rb.rsp.getReturnFields().wantsField(keyFieldName);
    if (rb.rsp.getReturnFields().getFieldRenames().get(keyFieldName) != null) {
      // if id was renamed we need to use the new name
      keyFieldName = rb.rsp.getReturnFields().getFieldRenames().get(keyFieldName);
    }

    for (ShardResponse srsp : sreq.responses) {
      if (srsp.getException() != null) {
        // Don't try to get the documents if there was an exception in the shard
        if(rb.req.getParams().getBool(ShardParams.SHARDS_INFO, false)) {
          @SuppressWarnings("unchecked")
          NamedList<Object> shardInfo = (NamedList<Object>) rb.rsp.getValues().get(ShardParams.SHARDS_INFO);
          @SuppressWarnings("unchecked")
          SimpleOrderedMap<Object> nl = (SimpleOrderedMap<Object>) shardInfo.get(srsp.getShard());
          if (nl.get("error") == null) {
            // Add the error to the shards info section if it wasn't added before
            Throwable t = srsp.getException();
            if(t instanceof SolrServerException) {
              t = ((SolrServerException)t).getCause();
            }
            nl.add("error", t.toString() );
            StringWriter trace = new StringWriter();
            t.printStackTrace(new PrintWriter(trace));
            nl.add("trace", trace.toString() );
          }
        }
        
        continue;
      }
      {
        NamedList<?> responseHeader = (NamedList<?>)srsp.getSolrResponse().getResponse().get("responseHeader");
        if (Boolean.TRUE.equals(responseHeader.getBooleanArg(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY))) {
          rb.rsp.getResponseHeader().asShallowMap()
             .put(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY, Boolean.TRUE);
        }
      }
      SolrDocumentList docs = (SolrDocumentList) srsp.getSolrResponse().getResponse().get("response");
      for (SolrDocument doc : docs) {
        Object id = doc.getFieldValue(keyFieldName);
        ShardDoc sdoc = rb.resultIds.get(id.toString());
        if (sdoc != null) {
          if (returnScores) {
            doc.setField("score", sdoc.score);
          } else {
            // Score might have been added (in createMainQuery) to shard-requests (and therefore in shard-response-docs)
            // Remove score if the outer request did not ask for it returned
            doc.remove("score");
          }
          if (removeKeyField) {
            doc.removeFields(keyFieldName);
          }
          rb.getResponseDocs().set(sdoc.positionInResponse, doc);
        }
      }
    }
  }
}
 
Example 17
Source File: SecureRealTimeGetComponent.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
@Override
public void transform(SolrDocument doc, int docid) {
  doc.setField( name, docid );
}
 
Example 18
Source File: ValueSourceAugmenter.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
protected void setValue(SolrDocument doc, Object val) {
  if(val!=null) {
    doc.setField( name, val );
  }
}
 
Example 19
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 20
Source File: ScoreAugmenter.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public void transform(SolrDocument doc, int docid, float score) {
  if( context != null && context.wantsScores() ) {
      doc.setField( name, score );
  }
}