Search in sources :

Example 26 with SolrDocument

use of org.apache.solr.common.SolrDocument in project lucene-solr by apache.

the class XMLWriter method writeSolrDocument.

/**
   * The SolrDocument should already have multivalued fields implemented as
   * Collections -- this will not rewrite to <arr>
   */
@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)) {
            System.out.println(val);
        }
        writeVal(fname, val);
    }
    if (doc.hasChildDocuments()) {
        for (SolrDocument childDoc : doc.getChildDocuments()) {
            writeSolrDocument(null, childDoc, new SolrReturnFields(), idx);
        }
    }
    decLevel();
    writer.write("</doc>");
}
Also used : SolrDocument(org.apache.solr.common.SolrDocument) SolrReturnFields(org.apache.solr.search.SolrReturnFields)

Example 27 with SolrDocument

use of org.apache.solr.common.SolrDocument in project lucene-solr by apache.

the class ChildDocTransformer method transform.

@Override
public void transform(SolrDocument doc, int docid, float score) {
    FieldType idFt = idField.getType();
    Object parentIdField = doc.getFirstValue(idField.getName());
    String parentIdExt = parentIdField instanceof IndexableField ? idFt.toExternal((IndexableField) parentIdField) : parentIdField.toString();
    try {
        Query parentQuery = idFt.getFieldQuery(null, idField, parentIdExt);
        Query query = new ToChildBlockJoinQuery(parentQuery, parentsFilter);
        DocList children = context.getSearcher().getDocList(query, childFilterQuery, new Sort(), 0, limit);
        if (children.matches() > 0) {
            DocIterator i = children.iterator();
            while (i.hasNext()) {
                Integer childDocNum = i.next();
                Document childDoc = context.getSearcher().doc(childDocNum);
                SolrDocument solrChildDoc = DocsStreamer.convertLuceneDocToSolrDoc(childDoc, schema);
                // TODO: future enhancement...
                // support an fl local param in the transformer, which is used to build
                // a private ReturnFields instance that we use to prune unwanted field 
                // names from solrChildDoc
                doc.addChildDocument(solrChildDoc);
            }
        }
    } catch (IOException e) {
        doc.put(name, "Could not fetch child Documents");
    }
}
Also used : DocIterator(org.apache.solr.search.DocIterator) Query(org.apache.lucene.search.Query) ToChildBlockJoinQuery(org.apache.lucene.search.join.ToChildBlockJoinQuery) IOException(java.io.IOException) SolrDocument(org.apache.solr.common.SolrDocument) Document(org.apache.lucene.document.Document) ToChildBlockJoinQuery(org.apache.lucene.search.join.ToChildBlockJoinQuery) FieldType(org.apache.solr.schema.FieldType) IndexableField(org.apache.lucene.index.IndexableField) SolrDocument(org.apache.solr.common.SolrDocument) Sort(org.apache.lucene.search.Sort) DocList(org.apache.solr.search.DocList)

Example 28 with SolrDocument

use of org.apache.solr.common.SolrDocument in project lucene-solr by apache.

the class GeoFieldUpdater method create.

@Override
public DocTransformer create(String display, SolrParams params, SolrQueryRequest req) {
    String fname = params.get("f", display);
    if (fname.startsWith("[") && fname.endsWith("]")) {
        fname = display.substring(1, display.length() - 1);
    }
    SchemaField sf = req.getSchema().getFieldOrNull(fname);
    if (sf == null) {
        throw new SolrException(ErrorCode.BAD_REQUEST, this.getClass().getSimpleName() + " using unknown field: " + fname);
    }
    if (!(sf.getType() instanceof AbstractSpatialFieldType)) {
        throw new SolrException(ErrorCode.BAD_REQUEST, "GeoTransformer requested non-spatial field: " + fname + " (" + sf.getType().getClass().getSimpleName() + ")");
    }
    final GeoFieldUpdater updater = new GeoFieldUpdater();
    updater.field = fname;
    updater.display = display;
    updater.display_error = display + "_error";
    ValueSource shapes = null;
    AbstractSpatialFieldType<?> sdv = (AbstractSpatialFieldType<?>) sf.getType();
    SpatialStrategy strategy = sdv.getStrategy(fname);
    if (strategy instanceof CompositeSpatialStrategy) {
        shapes = ((CompositeSpatialStrategy) strategy).getGeometryStrategy().makeShapeValueSource();
    } else if (strategy instanceof SerializedDVStrategy) {
        shapes = ((SerializedDVStrategy) strategy).makeShapeValueSource();
    }
    String writerName = params.get("w", "GeoJSON");
    updater.formats = strategy.getSpatialContext().getFormats();
    updater.writer = updater.formats.getWriter(writerName);
    if (updater.writer == null) {
        StringBuilder str = new StringBuilder();
        str.append("Unknown Spatial Writer: ").append(writerName);
        str.append(" [");
        for (ShapeWriter w : updater.formats.getWriters()) {
            str.append(w.getFormatName()).append(' ');
        }
        str.append("]");
        throw new SolrException(ErrorCode.BAD_REQUEST, str.toString());
    }
    QueryResponseWriter qw = req.getCore().getQueryResponseWriter(req);
    updater.isJSON = (qw.getClass() == JSONResponseWriter.class) && (updater.writer instanceof GeoJSONWriter);
    // Using ValueSource
    if (shapes != null) {
        // we don't really need the qparser... just so we can reuse valueSource
        QParser parser = new QParser(null, null, params, req) {

            @Override
            public Query parse() throws SyntaxError {
                return new MatchAllDocsQuery();
            }
        };
        return new ValueSourceAugmenter(display, parser, shapes) {

            @Override
            protected void setValue(SolrDocument doc, Object val) {
                updater.setValue(doc, val);
            }
        };
    }
    // Using the raw stored values
    return new DocTransformer() {

        @Override
        public void transform(SolrDocument doc, int docid, float score) throws IOException {
            Object val = doc.remove(updater.field);
            if (val != null) {
                updater.setValue(doc, val);
            }
        }

        @Override
        public String getName() {
            return updater.display;
        }

        @Override
        public String[] getExtraRequestFields() {
            return new String[] { updater.field };
        }
    };
}
Also used : CompositeSpatialStrategy(org.apache.lucene.spatial.composite.CompositeSpatialStrategy) JSONResponseWriter(org.apache.solr.response.JSONResponseWriter) ShapeWriter(org.locationtech.spatial4j.io.ShapeWriter) AbstractSpatialFieldType(org.apache.solr.schema.AbstractSpatialFieldType) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) CompositeSpatialStrategy(org.apache.lucene.spatial.composite.CompositeSpatialStrategy) SpatialStrategy(org.apache.lucene.spatial.SpatialStrategy) SerializedDVStrategy(org.apache.lucene.spatial.serialized.SerializedDVStrategy) SchemaField(org.apache.solr.schema.SchemaField) SolrDocument(org.apache.solr.common.SolrDocument) ValueSource(org.apache.lucene.queries.function.ValueSource) QParser(org.apache.solr.search.QParser) QueryResponseWriter(org.apache.solr.response.QueryResponseWriter) GeoJSONWriter(org.locationtech.spatial4j.io.GeoJSONWriter) SolrException(org.apache.solr.common.SolrException)

Example 29 with SolrDocument

use of org.apache.solr.common.SolrDocument in project lucene-solr by apache.

the class DocsStreamer method next.

public SolrDocument next() {
    int id = docIterator.nextDoc();
    idx++;
    SolrDocument sdoc = null;
    if (onlyPseudoFields) {
        // no need to get stored fields of the document, see SOLR-5968
        sdoc = new SolrDocument();
    } else {
        try {
            Document doc = docFetcher.doc(id, fnames);
            // make sure to use the schema from the searcher and not the request (cross-core)
            sdoc = convertLuceneDocToSolrDoc(doc, rctx.getSearcher().getSchema());
            // decorate the document with non-stored docValues fields
            if (dvFieldsToReturn != null) {
                docFetcher.decorateDocValueFields(sdoc, id, dvFieldsToReturn);
            }
        } catch (IOException e) {
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error reading document with docId " + id, e);
        }
    }
    if (transformer != null) {
        boolean doScore = rctx.wantsScores();
        try {
            transformer.transform(sdoc, id, doScore ? docIterator.score() : 0);
        } catch (IOException e) {
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error applying transformer", e);
        }
    }
    return sdoc;
}
Also used : SolrDocument(org.apache.solr.common.SolrDocument) IOException(java.io.IOException) Document(org.apache.lucene.document.Document) SolrDocument(org.apache.solr.common.SolrDocument) SolrException(org.apache.solr.common.SolrException)

Example 30 with SolrDocument

use of org.apache.solr.common.SolrDocument in project lucene-solr by apache.

the class XLSXWriter method writeResponse.

public void writeResponse(OutputStream out, LinkedHashMap<String, String> colNamesMap, LinkedHashMap<String, Integer> colWidthsMap) throws IOException {
    SolrParams params = req.getParams();
    Collection<String> fields = returnFields.getRequestedFieldNames();
    Object responseObj = rsp.getValues().get("response");
    boolean returnOnlyStored = false;
    if (fields == null || returnFields.hasPatternMatching()) {
        if (responseObj instanceof SolrDocumentList) {
            // get the list of fields from the SolrDocumentList
            if (fields == null) {
                fields = new LinkedHashSet<String>();
            }
            for (SolrDocument sdoc : (SolrDocumentList) responseObj) {
                fields.addAll(sdoc.getFieldNames());
            }
        } else {
            // get the list of fields from the index
            Iterable<String> all = req.getSearcher().getFieldNames();
            if (fields == null) {
                fields = Sets.newHashSet(all);
            } else {
                Iterables.addAll(fields, all);
            }
        }
        if (returnFields.wantsScore()) {
            fields.add("score");
        } else {
            fields.remove("score");
        }
        returnOnlyStored = true;
    }
    for (String field : fields) {
        if (!returnFields.wantsField(field)) {
            continue;
        }
        if (field.equals("score")) {
            XLField xlField = new XLField();
            xlField.name = "score";
            xlFields.put("score", xlField);
            continue;
        }
        SchemaField sf = schema.getFieldOrNull(field);
        if (sf == null) {
            FieldType ft = new StrField();
            sf = new SchemaField(field, ft);
        }
        // Return only stored fields, unless an explicit field list is specified
        if (returnOnlyStored && sf != null && !sf.stored()) {
            continue;
        }
        XLField xlField = new XLField();
        xlField.name = field;
        xlField.sf = sf;
        xlFields.put(field, xlField);
    }
    wb.addRow();
    //write header
    for (XLField xlField : xlFields.values()) {
        String printName = xlField.name;
        int colWidth = 14;
        String niceName = colNamesMap.get(xlField.name);
        if (niceName != null) {
            printName = niceName;
        }
        Integer niceWidth = colWidthsMap.get(xlField.name);
        if (niceWidth != null) {
            colWidth = niceWidth.intValue();
        }
        writeStr(xlField.name, printName, false);
        wb.setColWidth(colWidth);
        wb.setHeaderCell();
    }
    wb.setHeaderRow();
    wb.addRow();
    if (responseObj instanceof ResultContext) {
        writeDocuments(null, (ResultContext) responseObj);
    } else if (responseObj instanceof DocList) {
        ResultContext ctx = new BasicResultContext((DocList) responseObj, returnFields, null, null, req);
        writeDocuments(null, ctx);
    } else if (responseObj instanceof SolrDocumentList) {
        writeSolrDocumentList(null, (SolrDocumentList) responseObj, returnFields);
    }
    wb.flush(out);
    wb = null;
}
Also used : BasicResultContext(org.apache.solr.response.BasicResultContext) ResultContext(org.apache.solr.response.ResultContext) StrField(org.apache.solr.schema.StrField) SolrDocumentList(org.apache.solr.common.SolrDocumentList) FieldType(org.apache.solr.schema.FieldType) SchemaField(org.apache.solr.schema.SchemaField) BasicResultContext(org.apache.solr.response.BasicResultContext) SolrDocument(org.apache.solr.common.SolrDocument) SolrParams(org.apache.solr.common.params.SolrParams) DocList(org.apache.solr.search.DocList)

Aggregations

SolrDocument (org.apache.solr.common.SolrDocument)230 SolrDocumentList (org.apache.solr.common.SolrDocumentList)93 QueryResponse (org.apache.solr.client.solrj.response.QueryResponse)81 ArrayList (java.util.ArrayList)50 SolrQuery (org.apache.solr.client.solrj.SolrQuery)47 Test (org.junit.Test)46 SolrParams (org.apache.solr.common.params.SolrParams)38 SolrServerException (org.apache.solr.client.solrj.SolrServerException)35 ModifiableSolrParams (org.apache.solr.common.params.ModifiableSolrParams)35 IOException (java.io.IOException)32 SolrInputDocument (org.apache.solr.common.SolrInputDocument)28 HashMap (java.util.HashMap)26 HttpSolrClient (org.apache.solr.client.solrj.impl.HttpSolrClient)24 NamedList (org.apache.solr.common.util.NamedList)21 Map (java.util.Map)20 List (java.util.List)18 SolrClient (org.apache.solr.client.solrj.SolrClient)13 ByteArrayInputStream (java.io.ByteArrayInputStream)12 UpdateRequest (org.apache.solr.client.solrj.request.UpdateRequest)12 SolrException (org.apache.solr.common.SolrException)12