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.temenos.interaction.commands.solr.AbstractSolrCommand.java

License:Open Source License

public CollectionResource<Entity> buildCollectionResource(String entityName, SolrDocumentList docs) {
    List<EntityResource<Entity>> results = new ArrayList<EntityResource<Entity>>();
    long numFound = docs.getNumFound();
    for (int i = 0; i < MAX_ENTITIES_RETURNED && i < numFound; i++) {
        EntityProperties properties = new EntityProperties();
        SolrDocument doc = docs.get(i);//from   w  w  w  .j av a  2 s. co  m
        Collection<String> fields = doc.getFieldNames();
        for (String propName : fields) {
            properties.setProperty(new EntityProperty(propName, doc.getFirstValue(propName)));
        }
        // Give some control to user if they have something in mind
        customizeEntityProperties(doc, properties);

        // Build the entity as is
        Entity entity = new Entity(entityName, properties);
        results.add(new EntityResource<Entity>(entityName, entity));
    }
    return new CollectionResource<Entity>(results) {
    };
}

From source file:com.tripod.solr.service.AbstractSolrService.java

License:Apache License

/**
 * Common logic for sub-classes to perform searches.
 *
 * @param query the query/*from   ww  w .j  ava2  s  . c om*/
 * @return the QueryResults
 * @throws QueryException if an error ocurred performing the search
 */
protected QueryResults<QR> performSearch(Q query) throws QueryException {
    try {
        // Convert from Query API to SolrQuery
        final SolrQuery solrQuery = queryFactory.transform(query);
        final SolrRequest.METHOD method = getMethod(query);

        // Start the results builder with the offset and rows from the query
        final QueryResults.Builder<QR> resultsBuilder = new QueryResults.Builder<QR>().offset(query.getOffset())
                .pageSize(query.getRows());

        // Perform the actual Solr query
        long startTime = System.currentTimeMillis();
        final QueryResponse response = solrClient.query(solrQuery, method);
        LOGGER.debug("Query executed in " + (System.currentTimeMillis() - startTime));

        final SolrDocumentList solrDocs = response.getResults();
        final Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();

        // Transform each Solr doc to a QueryResult and add highlights if they exist
        for (SolrDocument solrDoc : solrDocs) {
            final QR queryResult = solrDocumentTransformer.transform(solrDoc);
            if (queryResult != null) {
                processHighlighting(queryResult, highlighting);
                resultsBuilder.addResult(queryResult);
            }
        }

        // Process faceting results
        final List<FacetField> facetFields = response.getFacetFields();
        processFacetResults(resultsBuilder, facetFields);

        resultsBuilder.totalResults(solrDocs.getNumFound());
        return resultsBuilder.build();

    } catch (SolrServerException e) {
        LOGGER.error(e.getMessage(), e);
        throw new QueryException("An unexpected error occurred performing the search operation", e);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        throw new QueryException("An unexpected error occurred communicating with the query service", e);
    } catch (TransformException e) {
        throw new QueryException("A transform error occurred", e);
    }
}

From source file:com.welab.x.blacklist.impl.BlackList.java

License:Open Source License

/**
 * Common method to build a query result set.
 * /*from  ww  w . j a  va2s. co  m*/
 * @param docs
 * @return QueryResultSet
 */
private QueryResultSet buildQueryResultSet(final SolrDocumentList docs) {
    QueryResultSet queryResultSet = new QueryResultSet();
    if (docs != null) {
        queryResultSet.setNumberFound(docs.getNumFound());
        queryResultSet.setIsExists(docs.getNumFound() == 0 ? false : true);
        List<QueryResult> queryResultList = new ArrayList<QueryResult>();
        QueryResult qresult;

        Iterator<SolrDocument> iter = docs.iterator();
        while (iter.hasNext()) {
            qresult = new QueryResult();
            SolrDocument resultDoc = iter.next();
            if (resultDoc.getFieldValue("content") != null) {
                qresult.setContent(resultDoc.getFieldValue("content").toString());
            }
            if (resultDoc.getFieldValue("id") != null) {
                qresult.setId(resultDoc.getFieldValue("id").toString());
            }
            if (resultDoc.getFieldValue("segment") != null) {
                qresult.setSegment(resultDoc.getFieldValue("segment").toString());
            }
            if (resultDoc.getFieldValue("tstamp") != null) {
                qresult.setTimeStamp(resultDoc.getFieldValue("tstamp").toString());
            }
            if (resultDoc.getFieldValue("title") != null) {
                qresult.setTitle(resultDoc.getFieldValue("title").toString());
            }
            if (resultDoc.getFieldValue("url") != null) {
                qresult.setUrl(resultDoc.getFieldValue("url").toString());
            }
            queryResultList.add(qresult);
        }
        queryResultSet.setQueryResult(queryResultList);
    }

    return queryResultSet;
}

From source file:com.yahoo.ycsb.db.solr.SolrClient.java

License:Open Source License

/**
 * Read a record from the database. Each field/value pair from the result will be stored in a
 * HashMap.//from w  w  w.j  a  va2 s .  c  o  m
 *
 * @param table
 *          The name of the table
 * @param key
 *          The record key of the record to read.
 * @param fields
 *          The list of fields to read, or null for all of them
 * @param result
 *          A HashMap of field/value pairs for the result
 * @return Zero on success, a non-zero error code on error or "not found".
 */
@Override
public Status read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) {
    try {
        Boolean returnFields = false;
        String[] fieldList = null;
        if (fields != null) {
            returnFields = true;
            fieldList = fields.toArray(new String[fields.size()]);
        }
        SolrQuery query = new SolrQuery();
        query.setQuery("id:" + key);
        if (returnFields) {
            query.setFields(fieldList);
        }
        final QueryResponse response = client.query(table, query);
        SolrDocumentList results = response.getResults();
        if ((results != null) && (results.getNumFound() > 0)) {
            for (String field : results.get(0).getFieldNames()) {
                result.put(field, new StringByteIterator(String.valueOf(results.get(0).getFirstValue(field))));
            }
        }
        return checkStatus(response.getStatus());
    } catch (IOException | SolrServerException e) {
        e.printStackTrace();
    }
    return Status.ERROR;
}

From source file:com.yahoo.ycsb.db.solr.SolrClient.java

License:Open Source License

/**
 * Perform a range scan for a set of records in the database. Each field/value pair from the
 * result will be stored in a HashMap.//from  ww  w  .ja  v a  2  s. c  om
 *
 * @param table
 *          The name of the table
 * @param startkey
 *          The record key of the first record to read.
 * @param recordcount
 *          The number of records to read
 * @param fields
 *          The list of fields to read, or null for all of them
 * @param result
 *          A Vector of HashMaps, where each HashMap is a set field/value pairs for one record
 * @return Zero on success, a non-zero error code on error. See this class's description for a
 *         discussion of error codes.
 */
@Override
public Status scan(String table, String startkey, int recordcount, Set<String> fields,
        Vector<HashMap<String, ByteIterator>> result) {
    try {
        Boolean returnFields = false;
        String[] fieldList = null;
        if (fields != null) {
            returnFields = true;
            fieldList = fields.toArray(new String[fields.size()]);
        }
        SolrQuery query = new SolrQuery();
        query.setQuery("*:*");
        query.setParam("fq", "id:[ " + startkey + " TO * ]");
        if (returnFields) {
            query.setFields(fieldList);
        }
        query.setRows(recordcount);
        final QueryResponse response = client.query(table, query);
        SolrDocumentList results = response.getResults();

        HashMap<String, ByteIterator> entry;

        for (SolrDocument hit : results) {
            entry = new HashMap<String, ByteIterator>((int) results.getNumFound());
            for (String field : hit.getFieldNames()) {
                entry.put(field, new StringByteIterator(String.valueOf(hit.getFirstValue(field))));
            }
            result.add(entry);
        }
        return checkStatus(response.getStatus());
    } catch (IOException | SolrServerException e) {
        e.printStackTrace();
    }
    return Status.ERROR;
}

From source file:com.yahoo.ycsb.db.solr6.SolrClient.java

License:Open Source License

/**
 * Perform a range scan for a set of records in the database. Each field/value pair from the
 * result will be stored in a HashMap./*from  w w w.  java  2 s  .co m*/
 *
 * @param table
 *          The name of the table
 * @param startkey
 *          The record key of the first record to read.
 * @param recordcount
 *          The number of records to read
 * @param fields
 *          The list of fields to read, or null for all of them
 * @param result
 *          A Vector of HashMaps, where each HashMap is a set field/value pairs for one record
 * @return Zero on success, a non-zero error code on error. See this class's description for a
 *         discussion of error codes.
 */
@Override
public Status scan(String table, String startkey, int recordcount, Set<String> fields,
        Vector<HashMap<String, ByteIterator>> result) {
    try {
        Boolean returnFields = false;
        String[] fieldList = null;
        if (fields != null) {
            returnFields = true;
            fieldList = fields.toArray(new String[fields.size()]);
        }
        SolrQuery query = new SolrQuery();
        query.setQuery("*:*");
        query.setParam("fq", "id:[ " + startkey + " TO * ]");
        if (returnFields) {
            query.setFields(fieldList);
        }
        query.setRows(recordcount);
        final QueryResponse response = client.query(table, query);
        SolrDocumentList results = response.getResults();

        HashMap<String, ByteIterator> entry;

        for (SolrDocument hit : results) {
            entry = new HashMap<>((int) results.getNumFound());
            for (String field : hit.getFieldNames()) {
                entry.put(field, new StringByteIterator(String.valueOf(hit.getFirstValue(field))));
            }
            result.add(entry);
        }
        return checkStatus(response.getStatus());
    } catch (IOException | SolrServerException e) {
        e.printStackTrace();
    }
    return Status.ERROR;
}

From source file:com.yaotrue.learn.solr.SolrjTest.java

License:Apache License

@Test
public void testSuggest() throws SolrServerException, IOException {
    SolrQuery params = new SolrQuery();
    params.set("qt", "/suggest");
    params.set("suggest", true);
    params.set("suggest.dictionary", "mySuggester");
    params.set("suggest.q", "?");
    QueryResponse query = solrClient.query(params);
    NamedList<Object> response = query.getResponse();
    //      response.get("suggest")
    SpellCheckResponse spellCheckResponse = query.getSpellCheckResponse();
    List<Suggestion> suggestions = spellCheckResponse.getSuggestions();
    for (Suggestion suggestion : suggestions) {//JAVA
        List<String> suggestions2 = suggestion.getAlternatives();
        for (String string : suggestions2) {
            System.out.println(string);
        }/*from w ww  . j a v  a 2 s  .c om*/
    }
    SolrDocumentList results = query.getResults();
    for (int i = 0; i < results.getNumFound(); i++) {
        System.out.println(results.get(i).get("suggestion"));
    }
}

From source file:cz.incad.vdkcommon.solr.Indexer.java

License:Open Source License

public void removeAllWanted() throws Exception {
    SolrQuery query = new SolrQuery("chci:[* TO *]");
    query.addField("code");
    SolrDocumentList docs = IndexerQuery.query(query);
    long numFound = docs.getNumFound();
    Iterator<SolrDocument> iter = docs.iterator();
    while (iter.hasNext()) {
        if (jobData.isInterrupted()) {
            LOGGER.log(Level.INFO, "INDEXER INTERRUPTED");
            break;
        }//  w w  w  .ja  v a2s. c o  m
        StringBuilder sb = new StringBuilder();

        SolrDocument resultDoc = iter.next();
        String docCode = (String) resultDoc.getFieldValue("code");
        sb.append("<add><doc>");
        sb.append("<field name=\"code\">").append(docCode).append("</field>");
        sb.append("<field name=\"md5\">").append(docCode).append("</field>");

        sb.append("<field name=\"chci\" update=\"set\" null=\"true\" />");
        sb.append("</doc></add>");
        SolrIndexerCommiter.postData(sb.toString());
        SolrIndexerCommiter.postData("<commit/>");
    }
    query.setQuery("nechci:[* TO *]");
    query.addField("code");
    docs = IndexerQuery.query(query);
    iter = docs.iterator();
    while (iter.hasNext()) {
        if (jobData.isInterrupted()) {
            LOGGER.log(Level.INFO, "INDEXER INTERRUPTED");
            break;
        }
        StringBuilder sb = new StringBuilder();

        SolrDocument resultDoc = iter.next();
        String docCode = (String) resultDoc.getFieldValue("code");
        sb.append("<add><doc>");
        sb.append("<field name=\"code\">").append(docCode).append("</field>");
        sb.append("<field name=\"md5\">").append(docCode).append("</field>");

        sb.append("<field name=\"nechci\" update=\"set\" null=\"true\" />");
        sb.append("</doc></add>");
        SolrIndexerCommiter.postData(sb.toString());
        SolrIndexerCommiter.postData("<commit/>");
    }

    numFound += docs.getNumFound();
    if (numFound > 0 && !jobData.isInterrupted()) {
        removeAllWanted();
    }
}

From source file:cz.incad.vdkcommon.solr.Indexer.java

License:Open Source License

public void removeAllOffers() throws Exception {
    SolrQuery query = new SolrQuery("nabidka:[* TO *]");
    query.addField("code");
    SolrDocumentList docs = IndexerQuery.query(query);
    Iterator<SolrDocument> iter = docs.iterator();
    while (iter.hasNext()) {
        if (jobData.isInterrupted()) {
            LOGGER.log(Level.INFO, "INDEXER INTERRUPTED");
            break;
        }//  w  ww.  j a va 2s  .c  o  m
        StringBuilder sb = new StringBuilder();

        SolrDocument resultDoc = iter.next();
        String docCode = (String) resultDoc.getFieldValue("code");
        sb.append("<add><doc>");
        sb.append("<field name=\"code\">").append(docCode).append("</field>");
        sb.append("<field name=\"md5\">").append(docCode).append("</field>");

        sb.append("<field name=\"nabidka\" update=\"set\" null=\"true\" />");
        sb.append("<field name=\"nabidka_ext\" update=\"set\" null=\"true\" />");
        sb.append("<field name=\"nabidka_datum\" update=\"set\" null=\"true\" />");
        sb.append("</doc></add>");
        SolrIndexerCommiter.postData(sb.toString());
        SolrIndexerCommiter.postData("<commit/>");
    }

    long numFound = docs.getNumFound();
    if (numFound > 0 && !jobData.isInterrupted()) {
        removeAllOffers();
    }
}

From source file:cz.incad.vdkcommon.solr.Indexer.java

License:Open Source License

public void removeAllDemands() throws Exception {
    SolrQuery query = new SolrQuery("poptavka:[* TO *]");
    query.addField("code");
    query.setRows(1000);/* w ww .  ja v  a 2  s.c  o  m*/
    SolrDocumentList docs = IndexerQuery.query(query);
    long numFound = docs.getNumFound();
    Iterator<SolrDocument> iter = docs.iterator();
    while (iter.hasNext()) {
        if (jobData.isInterrupted()) {
            LOGGER.log(Level.INFO, "INDEXER INTERRUPTED");
            break;
        }
        StringBuilder sb = new StringBuilder();

        SolrDocument resultDoc = iter.next();
        String docCode = (String) resultDoc.getFieldValue("code");
        sb.append("<add><doc>");
        sb.append("<field name=\"code\">").append(docCode).append("</field>");
        sb.append("<field name=\"md5\">").append(docCode).append("</field>");

        sb.append("<field name=\"poptavka\" update=\"set\" null=\"true\" />");
        sb.append("<field name=\"poptavka_ext\" update=\"set\" null=\"true\" />");
        sb.append("</doc></add>");
        SolrIndexerCommiter.postData(sb.toString());
        SolrIndexerCommiter.postData("<commit/>");
        LOGGER.log(Level.INFO, "Demands for {0} removed.", docCode);
    }
    if (numFound > 0 && !jobData.isInterrupted()) {
        removeAllDemands();
    }
}