Example usage for org.apache.solr.common SolrDocumentList getNumFound

List of usage examples for org.apache.solr.common SolrDocumentList getNumFound

Introduction

In this page you can find the example usage for org.apache.solr.common SolrDocumentList getNumFound.

Prototype

public long getNumFound() 

Source Link

Usage

From source file:com.nridge.ds.solr.SolrDS.java

License:Open Source License

/**
 * Calculates a count (using a wildcard criteria) of all the
 * rows stored in the content source and returns that value.
 *
 * @return Count of all rows in the content source.
 * @throws DSException Data source related exception.
 *///from ww  w .j  a  v  a  2  s  .  c o m
@Override
public int count() throws DSException {
    int documentCount;
    Logger appLogger = mAppMgr.getLogger(this, "count");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    initialize();

    DSCriteria dsCriteria = new DSCriteria("Solr Query");
    dsCriteria.add(Solr.FIELD_QUERY_NAME, Field.Operator.EQUAL, Solr.QUERY_ALL_DOCUMENTS);

    SolrQuery solrQuery = mSolrQueryBuilder.create(dsCriteria);
    solrQuery.setStart(0);
    solrQuery.setRows(1);

    appLogger.debug(String.format("%s: %s %s", dsCriteria.getName(), mSolrIdentity, solrQuery.toString()));

    QueryResponse queryResponse = queryExecute(solrQuery);
    SolrDocumentList solrDocumentList = queryResponse.getResults();
    documentCount = (int) solrDocumentList.getNumFound();

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return documentCount;
}

From source file:com.nridge.ds.solr.SolrDS.java

License:Open Source License

/**
 * Returns a count of rows that match the <i>DSCriteria</i> specified
 * in the parameter./*from w ww  .jav a 2  s . co  m*/
 *
 * @param aDSCriteria Data source criteria.
 *
 * @return Count of rows matching the data source criteria.
 *
 * @throws com.nridge.core.base.ds.DSException Data source related exception.
 */
@Override
public int count(DSCriteria aDSCriteria) throws DSException {
    int documentCount;
    Logger appLogger = mAppMgr.getLogger(this, "count");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    initialize();

    SolrQuery solrQuery = mSolrQueryBuilder.create(aDSCriteria);
    solrQuery.setStart(0);
    solrQuery.setRows(1);

    appLogger.debug(String.format("%s: %s %s", aDSCriteria.getName(), mSolrIdentity, solrQuery.toString()));

    QueryResponse queryResponse = queryExecute(solrQuery);
    SolrDocumentList solrDocumentList = queryResponse.getResults();
    documentCount = (int) solrDocumentList.getNumFound();

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return documentCount;
}

From source file:com.nridge.ds.solr.SolrResponseBuilder.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
private void populateHeader(QueryResponse aQueryResponse, long anOffset, long aLimit) {
    Logger appLogger = mAppMgr.getLogger(this, "populateHeader");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    Relationship headerRelationship = mDocument.getFirstRelationship(Solr.RESPONSE_HEADER);
    if (headerRelationship != null) {
        DataBag headerBag = headerRelationship.getBag();
        headerBag.resetValues();// w  w  w .ja va  2  s .  c om

        headerBag.setValueByName("page_size", aLimit);
        headerBag.setValueByName("offset_start", anOffset);
        headerBag.setValueByName("query_time", aQueryResponse.getQTime());

        String propertyName = getCfgPropertyPrefix() + ".request_handler";
        String requestHandler = mAppMgr.getString(propertyName);
        if (StringUtils.isNotEmpty(requestHandler)) {
            if (requestHandler.charAt(0) == StrUtl.CHAR_FORWARDSLASH)
                headerBag.setValueByName("request_handler", requestHandler);
            else
                headerBag.setValueByName("request_handler", StrUtl.CHAR_FORWARDSLASH + requestHandler);
        }

        int statusCode = aQueryResponse.getStatus();
        headerBag.setValueByName("status_code", statusCode);
        if (statusCode == Solr.RESPONSE_STATUS_SUCCESS)
            headerBag.setValueByName("status_message", "Success");
        else
            headerBag.setValueByName("status_message", "Failure");

        SolrDocumentList solrDocumentList = aQueryResponse.getResults();
        if (solrDocumentList != null) {
            Float maxScore = solrDocumentList.getMaxScore();
            if (maxScore == null)
                maxScore = (float) 0.0;
            headerBag.setValueByName("max_score", maxScore);
            headerBag.setValueByName("fetch_count", solrDocumentList.size());
            long totalCount = solrDocumentList.getNumFound();
            headerBag.setValueByName("total_count", totalCount);
        }

        NamedList<Object> headerList = aQueryResponse.getHeader();
        if (headerList != null) {
            NamedList<Object> paramList = (NamedList<Object>) aQueryResponse.getResponseHeader().get("params");
            if (paramList != null) {
                Object paramObject = paramList.get("fl");
                if (paramObject != null) {
                    DataField dataField = headerBag.getFieldByName("field_list");
                    if (paramObject instanceof String)
                        dataField.addValue(paramObject.toString());
                    else if (paramObject instanceof List) {
                        List fieldList = (List) paramObject;
                        int fieldCount = fieldList.size();
                        if (fieldCount > 0) {
                            for (int i = 0; i < fieldCount; i++)
                                dataField.addValue(fieldList.get(i).toString());
                        }
                    }
                }
                paramObject = paramList.get("hl");
                if (paramObject != null) {
                    DataField dataField = headerBag.getFieldByName("is_highlighted");
                    if (paramObject instanceof String) {
                        if (StringUtils.equalsIgnoreCase(paramObject.toString(), "on"))
                            dataField.setValue(true);
                    }
                }
            }
        }
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.nridge.ds.solr.SolrResponseBuilder.java

License:Open Source License

private void populateMoreLikeThis(QueryResponse aQueryResponse) {
    String docName;/*from   w  w  w.  java 2 s . c  o m*/
    Document mltDocument;
    DataField docNameField;
    SolrDocumentList solrDocumentList;
    Logger appLogger = mAppMgr.getLogger(this, "populateMoreLikeThis");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    NamedList<SolrDocumentList> mltDocuments = aQueryResponse.getMoreLikeThis();
    if (mltDocuments != null) {
        mDocument.addRelationship(Solr.RESPONSE_MORE_LIKE_THIS, createMLTBag());
        Relationship mltRelationship = mDocument.getFirstRelationship(Solr.RESPONSE_MORE_LIKE_THIS);
        if (mltRelationship != null) {
            int mltCount = mltDocuments.size();
            DataBag mltBag = mltRelationship.getBag();
            docNameField = mltBag.getFieldByName("mlt_name");
            mltBag.setValueByName("mlt_total", mltCount);
            for (int i = 0; i < mltCount; i++) {
                docName = mltDocuments.getName(i);
                docNameField.addValue(docName);
                solrDocumentList = mltDocuments.getVal(i);
                if (solrDocumentList.getNumFound() > 0L) {
                    mltDocument = new Document(Solr.RESPONSE_MLT_DOCUMENT, createDocumentTable());
                    populateDocument(mltDocument, solrDocumentList);
                    mltRelationship.add(mltDocument);
                }
            }
        }
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.nridge.ds.solr.SolrResponseBuilder.java

License:Open Source License

@SuppressWarnings("unchecked")
private Document createGroupCollectionDocument(Group aGroup) {
    Logger appLogger = mAppMgr.getLogger(this, "createGroupCollectionDocument");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    Document groupCollectionDocument = createGroupCollection();
    DataBag groupCollectionBag = groupCollectionDocument.getBag();

    String groupName = aGroup.getGroupValue();
    if (StringUtils.isNotEmpty(groupName))
        groupCollectionBag.setValueByName("group_name", groupName);
    SolrDocumentList solrDocumentList = aGroup.getResult();
    if (solrDocumentList != null) {
        groupCollectionBag.setValueByName("offset_start", solrDocumentList.getStart());
        groupCollectionBag.setValueByName("total_count", solrDocumentList.getNumFound());
        Document groupDocument = new Document(Solr.RESPONSE_GROUP_DOCUMENT, createDocumentTable());
        populateDocument(groupDocument, solrDocumentList);
        groupCollectionDocument.addRelationship(groupDocument.getType(), groupDocument);
    }/*from   w w  w  . j a  v a  2  s  . co  m*/

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return groupCollectionDocument;
}

From source file:com.riemersebastian.solrduplicate.SolrDuplicateTest.java

private void executeQueryAndShowResults() {
    LOGGER.info("List all documents with id = 'parent_1' ");
    try {/*from  w w  w.  jav  a  2s  .c o m*/
        SolrQuery query = new SolrQuery();
        query.add("q", "*:*");
        query.add("fq", "id:parent_1");
        QueryResponse response = solrClient.query(query);
        SolrDocumentList results = response.getResults();
        for (SolrDocument doc : results) {
            LOGGER.info("Found document with id = '" + doc.get("id") + "'");
        }
        LOGGER.info("Found a total of " + results.getNumFound() + " documents having id='parent_1'.");
    } catch (SolrServerException | IOException ex) {
        LOGGER.log(Level.SEVERE, "Exception while querying index!", ex);
    }
}

From source file:com.sindicetech.siren.solr.analysis.TestASCIIFoldingExpansionFilterFactory.java

License:Open Source License

/**
 * SRN-96/*from  ww w  . j a  va2  s . co  m*/
 */
@Test
public void testASCIIFoldingExpansion() throws IOException, SolrServerException {
    this.addJsonString("1", " { \"value\" : \"cafe\" } ");
    this.addJsonString("2", " { \"value\" : \"caf\" } ");
    SolrQuery query = new SolrQuery();
    query.setQuery("cafe");
    query.setRequestHandler("keyword");
    query.setIncludeScore(true);

    // should match the two documents, with same score
    QueryResponse response = getWrapper().getServer().query(query);
    SolrDocumentList docList = response.getResults();
    assertEquals(2, docList.getNumFound());
    float score1 = (Float) docList.get(0).getFieldValue("score");
    float score2 = (Float) docList.get(1).getFieldValue("score");
    Assert.assertTrue("Score should be identical", score1 == score2);

    // should match the two documents, but should assign different score
    // id2 should receive better score than id1
    query = new SolrQuery();
    query.setQuery("caf");
    query.setRequestHandler("keyword");
    query.setIncludeScore(true);

    response = getWrapper().getServer().query(query);
    docList = response.getResults();
    assertEquals(2, docList.getNumFound());
    if (docList.get(0).getFieldValue("url").equals("id1")) {
        score1 = (Float) docList.get(0).getFieldValue("score");
        score2 = (Float) docList.get(1).getFieldValue("score");
    } else {
        score2 = (Float) docList.get(0).getFieldValue("score");
        score1 = (Float) docList.get(1).getFieldValue("score");
    }
    Assert.assertTrue("id2 should get higher score than id1", score1 < score2);
}

From source file:com.sindicetech.siren.solr.handler.TestSirenUpdateRequestHandler.java

License:Open Source License

/**
 * Check that a UUID is generated for JSON documents with no 'id' attribute.
 *///from w ww  .  j  a  va2 s  .  c om
@Test
public void testJsonWithNoId() throws IOException, SolrServerException {
    String input = "{ \"aaa\" :  \"bbb\" }";
    this.sendUpdateRequest(input);
    this.commit();

    SolrQuery query = new SolrQuery();
    query.setParam("nested", "{!lucene} *:*");
    query.setRequestHandler("tree");
    query.setFields(IdFieldMapper.INPUT_FIELD);

    SolrDocumentList results = this.search(query);
    assertEquals(1, results.getNumFound());
    assertNotNull(results.get(0).getFieldValue(IdFieldMapper.INPUT_FIELD));
}

From source file:com.sindicetech.siren.solr.handler.TestSirenUpdateRequestHandler.java

License:Open Source License

/**
 * Check if the field is stored as indicated by the fieldtype of the associated path-based mapper.
 *//*from w  w  w . j av  a2s. c o m*/
@Test
public void testStoredField() throws QueryNodeException, IOException, SolrServerException {
    String input = "{ \"id\" : \"1\", \"aaa\" :  \"bbb\" }";

    this.sendUpdateRequest(input);
    this.commit();

    SolrQuery query = new SolrQuery();
    final ConciseQueryBuilder b = new ConciseQueryBuilder();
    query.setQuery(b.newNode("bbb").setAttribute("aaa").toString());
    query.setRequestHandler("tree");
    query.setFields("aaa");

    SolrDocumentList result = this.search(query);
    assertEquals(1, result.getNumFound());
    assertNotNull(result.get(0).getFieldValue("aaa"));
    assertTrue(result.get(0).getFieldValue("aaa") instanceof ArrayList);
    assertEquals("bbb", ((ArrayList) result.get(0).getFieldValue("aaa")).get(0));
}

From source file:com.smartitengineering.dao.solr.impl.DefaultSolrDao.java

License:Open Source License

@Override
public SearchResult<MultivalueMap<String, Object>> getResult(SolrParams query) {
    boolean success = true;
    List<MultivalueMap<String, Object>> list = new ArrayList<MultivalueMap<String, Object>>();
    SearchResult<MultivalueMap<String, Object>> result = null;
    try {/*from   w w  w. java  2  s . co m*/
        final SolrServer solrServer = serverFactory.getSolrServer();
        QueryResponse response = solrServer.query(query);
        success = response.getStatus() == 0 && success;
        if (success) {
            SolrDocumentList documentList = response.getResults();
            if (logger.isInfoEnabled()) {
                logger.info("Solr Document List " + documentList);
            }
            if (documentList.getMaxScore() == null) {
                result = new SearchResult<MultivalueMap<String, Object>>(list, documentList.getNumFound());
            } else {
                result = new SearchResult<MultivalueMap<String, Object>>(list, documentList.getNumFound(),
                        documentList.getMaxScore());
            }
            for (SolrDocument document : documentList) {
                MultivalueMap<String, Object> map = new MultivalueMapImpl<String, Object>();
                list.add(map);
                Map<String, Collection<Object>> values = document.getFieldValuesMap();
                for (String key : values.keySet()) {
                    Collection<Object> oValues = values.get(key);
                    for (Object value : oValues) {
                        map.addValue(key, value);
                    }
                }
            }
        }
    } catch (Exception ex) {
        logger.error("Could not search from solr index", ex);
        success = false;
    }
    if (result == null) {
        result = new SearchResult<MultivalueMap<String, Object>>(list);
    }
    return result;
}