Example usage for org.apache.solr.common SolrDocument addField

List of usage examples for org.apache.solr.common SolrDocument addField

Introduction

In this page you can find the example usage for org.apache.solr.common SolrDocument addField.

Prototype

@SuppressWarnings("unchecked")
@Override
public void addField(String name, Object value) 

Source Link

Document

This will add a field to the document.

Usage

From source file:at.pagu.soldockr.core.convert.MappingSolrConverterTest.java

License:Apache License

@Test
public void testRead() {
    SolrDocument document = new SolrDocument();
    document.addField("stringProperty", "christoph");
    document.addField("intProperty", 32);

    ConvertableBean convertable = converter.read(ConvertableBean.class, (Map<String, Object>) document);

    Assert.assertEquals(document.getFieldValue("stringProperty"), convertable.getStringProperty());
    Assert.assertEquals(document.getFieldValue("intProperty"), convertable.getIntProperty());
}

From source file:au.org.aekos.shared.api.model.dataset.SharedSearchResultFactoryTest.java

License:Creative Commons License

/**
 * Can we tell when we ARE under embargo because the date is in the future?
 *//*from  www  .  jav a 2  s .  c  o m*/
@Test
public void testDetermineIsEmbargoedOnDate01() {
    Date today = new Date();
    Calendar calendar = new GregorianCalendar();
    calendar.add(Calendar.YEAR, 1);
    Date oneYearInTheFuture = calendar.getTime();
    SolrDocument solrDoc = new SolrDocument();
    solrDoc.addField(prop("index-names.embargo-date"), oneYearInTheFuture);
    boolean result = objectUnderTest.determineIsEmbargoedOnDate(solrDoc, today);
    assertThat(result, is(true));
}

From source file:au.org.aekos.shared.api.model.dataset.SharedSearchResultFactoryTest.java

License:Creative Commons License

/**
 * Can we tell when we are NOT under embargo because the date is in the past?
 *///from   w  ww . j  a v  a  2 s . com
@Test
public void testDetermineIsEmbargoedOnDate02() {
    Date today = new Date();
    Calendar calendar = new GregorianCalendar();
    calendar.add(Calendar.DAY_OF_MONTH, -1);
    Date yesterday = calendar.getTime();
    SolrDocument solrDoc = new SolrDocument();
    solrDoc.addField(prop("index-names.embargo-date"), yesterday);
    boolean result = objectUnderTest.determineIsEmbargoedOnDate(solrDoc, today);
    assertThat(result, is(false));
}

From source file:au.org.aekos.shared.api.model.dataset.SharedSearchResultFactoryTest.java

License:Creative Commons License

/**
 * Can we tell when we ARE under embargo because the date is today?
 *//*www  .j  a va  2s. c  o  m*/
@Test
public void testDetermineIsEmbargoedOnDate03() {
    Date today = new Date();
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(today);
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    calendar.set(Calendar.MILLISECOND, 999);
    Date justBeforeMidnightToday = calendar.getTime();
    SolrDocument solrDoc = new SolrDocument();
    solrDoc.addField(prop("index-names.embargo-date"), justBeforeMidnightToday);
    boolean result = objectUnderTest.determineIsEmbargoedOnDate(solrDoc, today);
    assertThat(result, is(true));
}

From source file:com.basho.yokozuna.handler.EntropyData.java

License:Open Source License

@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp)
        throws Exception, InstantiationException, IllegalAccessException {

    String contParam = req.getParams().get("continue");
    BytesRef cont = contParam != null ? decodeCont(contParam) : DEFAULT_CONT;

    // TODO: Make before required in handler config
    String before = req.getParams().get("before");
    if (before == null) {
        throw new Exception("Parameter 'before' is required");
    }/*  w  ww. jav  a 2s  .  co m*/
    int n = req.getParams().getInt("n", DEFAULT_N);
    SolrDocumentList docs = new SolrDocumentList();

    // Add docs here and modify object inline in code
    rsp.add("response", docs);

    try {
        SolrIndexSearcher searcher = req.getSearcher();
        AtomicReader rdr = searcher.getAtomicReader();
        BytesRef tmp = null;
        Terms terms = rdr.terms(ENTROPY_DATA_FIELD);
        TermsEnum te = terms.iterator(null);

        if (isContinue(cont)) {
            log.debug("continue from " + cont);

            TermsEnum.SeekStatus status = te.seekCeil(cont, true);

            if (status == TermsEnum.SeekStatus.END) {
                rsp.add("more", false);
                return;
            } else if (status == TermsEnum.SeekStatus.FOUND) {
                // If this term has already been seen then skip it.
                tmp = te.next();

                if (endOfItr(tmp)) {
                    rsp.add("more", false);
                    return;
                }
            } else if (status == TermsEnum.SeekStatus.NOT_FOUND) {
                tmp = te.next();
            }
        } else {
            tmp = te.next();
        }

        String text = null;
        String[] vals = null;
        String ts = null;
        String docId = null;
        String vectorClock = null;
        int count = 0;
        BytesRef current = null;

        while (!endOfItr(tmp) && count < n) {
            current = BytesRef.deepCopyOf(tmp);
            text = tmp.utf8ToString();
            log.debug("text: " + text);
            vals = text.split(" ");
            ts = vals[0];

            // TODO: what if null?
            if (!(ts.compareTo(before) < 0)) {
                rsp.add("more", false);
                docs.setNumFound(count);
                return;
            }

            docId = vals[1];
            vectorClock = vals[2];
            SolrDocument tmpDoc = new SolrDocument();
            tmpDoc.addField("doc_id", docId);
            tmpDoc.addField("base64_vclock", Base64.encodeBase64String(sha(vectorClock)));
            docs.add(tmpDoc);
            count++;
            tmp = te.next();
        }

        if (count < n) {
            rsp.add("more", false);
        } else {
            rsp.add("more", true);
            String newCont = Base64.encodeBase64URLSafeString(current.bytes);
            // The continue context for next req to start where
            // this one finished.
            rsp.add("continuation", newCont);
        }

        docs.setNumFound(count);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.doculibre.constellio.opensearch.OpenSearchSolrServer.java

License:Open Source License

@SuppressWarnings("unchecked")
private static SolrDocumentList parse(Element rootElement) throws IOException {
    SolrDocumentList solrDocumentList = new SolrDocumentList();
    Element channelElement = rootElement.element("channel");
    String totalResultsStr = channelElement.elementText(new QName("totalResults", NS_OPENSEARCH));
    String startIndexStr = channelElement.elementText(new QName("startIndex", NS_OPENSEARCH));
    long numFound = Long.parseLong(totalResultsStr);
    long start = Long.parseLong(startIndexStr);
    solrDocumentList.setNumFound(numFound);
    solrDocumentList.setStart(start);//from  w w w  .j  a v a2  s.  co  m

    for (Iterator<Element> it = channelElement.elementIterator("item"); it.hasNext();) {
        Element itemElement = it.next();
        String title = itemElement.elementText("title");
        String description = itemElement.elementText("description");
        String link = itemElement.elementText("link");

        title = CharSetUtils.convert(title, CharSetUtils.UTF_8, CharSetUtils.ISO_8859_1);
        description = CharSetUtils.convert(description, CharSetUtils.UTF_8, CharSetUtils.ISO_8859_1);
        link = CharSetUtils.convert(link, CharSetUtils.UTF_8, CharSetUtils.ISO_8859_1);

        SolrDocument solrDocument = new SolrDocument();
        solrDocument.addField("title", title);
        solrDocument.addField("description", description);
        solrDocument.addField("link", link);
        solrDocumentList.add(solrDocument);
    }
    return solrDocumentList;
}

From source file:com.francelabs.datafari.statistics.StatsProcessor.java

License:Apache License

public static void processStatsResponse(final QueryResponse queryResponse) throws Exception {
    final NamedList responseHeader = queryResponse.getResponseHeader();
    final FacetField QFacet = queryResponse.getFacetField("q");

    final Long numTot = queryResponse.getResults().getNumFound();

    final SolrDocumentList solrDocumentList = new SolrDocumentList();
    solrDocumentList.setNumFound(QFacet.getValueCount());
    solrDocumentList.setStart(0);/* w  ww  .  j av a  2  s  .c o  m*/

    if (numTot != 0) {
        final Map<String, FieldStatsInfo> stats = queryResponse.getFieldStatsInfo();
        final List<FieldStatsInfo> noHitsStats = stats.get("noHits").getFacets().get("q");
        final List<FieldStatsInfo> QTimeStats = stats.get("QTime").getFacets().get("q");
        List<FieldStatsInfo> positionClickTotStats = null;
        try {
            positionClickTotStats = stats.get("positionClickTot").getFacets().get("q");
        } catch (final Exception e) {

        }
        final List<FieldStatsInfo> clickStats = stats.get("click").getFacets().get("q");
        final List<FieldStatsInfo> numClicksStats = stats.get("numClicks").getFacets().get("q");
        final List<FieldStatsInfo> numFoundStats = stats.get("numFound").getFacets().get("q");

        final List<Count> QFacetValues = QFacet.getValues();

        final Map<String, SolrDocument> mapDocuments = new HashMap<String, SolrDocument>();

        for (int i = 0; i < QFacetValues.size(); i++) {
            final SolrDocument doc = new SolrDocument();
            final String query = QFacetValues.get(i).getName();

            final double count = QFacetValues.get(i).getCount();
            final double frequency = StatsUtils.round(count * 100 / numTot, 2, BigDecimal.ROUND_HALF_UP);

            doc.addField("query", query);

            doc.addField("count", count);
            doc.addField("frequency", frequency);
            mapDocuments.put(query, doc);
            solrDocumentList.add(doc);
        }

        for (int i = 0; i < QTimeStats.size(); i++) {
            final String query = QTimeStats.get(i).getName();
            final SolrDocument doc = mapDocuments.get(query);

            final int AVGHits = new Double((Double) numFoundStats.get(i).getMean()).intValue();
            final Double noHits = new Double((Double) noHitsStats.get(i).getSum());
            final int AVGQTime = new Double((Double) QTimeStats.get(i).getMean()).intValue();
            final int MAXQTime = new Double((Double) QTimeStats.get(i).getMax()).intValue();
            final double click = new Double((Double) clickStats.get(i).getSum());
            final double clickRatio = StatsUtils.round(click * 100 / (Double) doc.getFirstValue("count"), 2,
                    BigDecimal.ROUND_HALF_UP);
            if (click > 0) {
                final double AVGClickPosition = new Double((Double) positionClickTotStats.get(i).getSum()
                        / (Double) numClicksStats.get(i).getSum()).intValue();

                doc.addField("AVGClickPosition", AVGClickPosition);

            } else {
                doc.addField("AVGClickPosition", "-");
            }

            doc.addField("withClickRatio", clickRatio);
            doc.addField("AVGHits", AVGHits);
            doc.addField("numNoHits", noHits);
            doc.addField("withClick", click);
            doc.addField("AVGQTime", AVGQTime);
            doc.addField("MaxQTime", MAXQTime);
        }

    }

    final NamedList<Object> response = new SimpleOrderedMap<Object>();
    response.add("responseHeader", responseHeader);
    response.add("response", solrDocumentList);
    queryResponse.setResponse(response);
}

From source file:com.gu.solr.MergeUtils.java

License:Apache License

private static void addFields(Document luceneDoc, SolrDocument solrDoc, IndexSchema schema) {
    for (Fieldable f : (List<Fieldable>) luceneDoc.getFields()) {
        SchemaField sf = schema.getField(f.name());
        if (!schema.isCopyFieldTarget(sf)) {
            Object externalVal = sf.getType().toObject(f);
            solrDoc.addField(f.name(), externalVal);
        }//from  w w  w .  j  ava2  s  .  co m
    }
}

From source file:com.ibm.watson.developer_cloud.professor_languo.pipeline.primary_search.RetrieveAndRankSearcherTest.java

License:Open Source License

private void set_non_empty_repsonse() throws IngestionException {
    String uniqThreadDirPath = get_unique_thread_path();
    SolrDocumentList doclist = new SolrDocumentList();
    SolrDocument doc = new SolrDocument();
    File serFile = new File(uniqThreadDirPath).listFiles()[0];
    StackExchangeThread thread = StackExchangeThreadSerializer.deserializeThreadFromBinFile(serFile.getPath());

    final Document luceneDoc = new LuceneDocumentMapper().createDocument(thread);
    BytesRef bin = luceneDoc.getBinaryValue(IndexDocumentFieldName.SERIALIZED_THREAD.toString());
    doc.addField(IndexDocumentFieldName.SERIALIZED_THREAD.toString(), bin.bytes);
    doc.addField("score", Integer.MAX_VALUE);
    doc.addField("featureVector", Double.MAX_VALUE);
    doclist.add(doc);//from   ww  w.  j a v  a  2  s.c  o m
    set_response(doclist);
}

From source file:com.sn.solr.plugin.common.SolrHelper.java

License:Apache License

/**
 * Constructs {@link SolrDocumentList} from the current {@link SolrQueryRequest}
 * and {@link SolrQueryResponse}.// w w w  .  j  a v a2s .  c  om
 * 
 * @param req {@link SolrQueryRequest}
 * @param res {@link SolrQueryResponse}
 * @return
 * @throws CorruptIndexException
 * @throws IOException
 */
public static SolrDocumentList getSolrDocList(SolrQueryRequest req, SolrQueryResponse res)
        throws CorruptIndexException, IOException {
    DocSlice slice = (DocSlice) res.getValues().get(RESP_EL_TAG);
    Set<String> returnFields = SolrHelper.getReturnFields(req);
    SolrDocumentList docList = new SolrDocumentList();
    for (DocIterator it = slice.iterator(); it.hasNext();) {
        int docId = it.nextDoc();
        Document doc = req.getSearcher().getReader().document(docId);
        SolrDocument sdoc = new SolrDocument();
        for (Fieldable f : doc.getFields()) {
            String fn = f.name();
            if (returnFields.contains(fn)) {
                sdoc.addField(fn, doc.get(fn));
            }
        }
        docList.add(sdoc);
    }
    docList.setMaxScore(slice.maxScore());
    docList.setNumFound(slice.matches());
    docList.setStart(slice.offset());
    return docList;
}