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:cn.edu.pku.lib.dataverse.SolrSearchServiceBean.java

public SolrSearchResult searchDataverseByName(String query, Locale locale) throws SearchException {
    boolean isZh = locale.getLanguage().equals("zh");
    SolrQuery solrQuery = new SolrQuery();
    StringBuilder queryStr = new StringBuilder();
    query = ClientUtils.escapeQueryChars(query);
    queryStr.append("(");
    queryStr.append(SearchFields.NAME);//from w w w  .  j  a v  a 2 s. co m
    queryStr.append(":");
    queryStr.append(query);
    queryStr.append(" OR ");
    queryStr.append(SearchFields.NAME_ZH);
    queryStr.append(":");
    queryStr.append(query);
    queryStr.append(")");
    solrQuery.setQuery(queryStr.toString());
    solrQuery.setFilterQueries(SearchFields.TYPE + ":dataverses",
            SearchFields.PUBLICATION_STATUS + ":Published");
    if (isZh) {
        solrQuery.setFields(SearchFields.ENTITY_ID, SearchFields.NAME_ZH, SearchFields.DATAVERSE_AFFILIATION_ZH,
                SearchFields.DESCRIPTION_ZH);
    } else {
        solrQuery.setFields(SearchFields.ENTITY_ID, SearchFields.NAME, SearchFields.DATAVERSE_AFFILIATION,
                SearchFields.DESCRIPTION);
    }
    logger.log(Level.INFO, "Solr query:{0}", solrQuery);
    solrQuery.setRows(100);
    QueryResponse queryResponse = null;
    SolrSearchResult result = new SolrSearchResult();
    try {
        queryResponse = solrServer.query(solrQuery);
    } catch (HttpSolrServer.RemoteSolrException ex) {
        logger.log(Level.INFO, null, ex);
        result.setTotal(0);
        result.setResults(Collections.EMPTY_LIST);
        return result;
    } catch (SolrServerException ex) {
        throw new SearchException("Internal Dataverse Search Engine Error", ex);
    }
    SolrDocumentList docs = queryResponse.getResults();
    docs.getNumFound();
    Iterator<SolrDocument> iter = docs.iterator();
    List<Dataverse> dataverses = new ArrayList<>();
    while (iter.hasNext()) {
        SolrDocument solrDocument = iter.next();
        Dataverse dataverse = new Dataverse();
        if (isZh) {
            dataverse.setId((Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID));
            dataverse.setNameZh((String) solrDocument.getFieldValue(SearchFields.NAME_ZH));
            dataverse.setAffiliationZh(
                    (String) solrDocument.getFieldValue(SearchFields.DATAVERSE_AFFILIATION_ZH));
            dataverse.setDescriptionZh((String) solrDocument.getFieldValue(SearchFields.DESCRIPTION_ZH));
        } else {
            dataverse.setId((Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID));
            dataverse.setName((String) solrDocument.getFieldValue(SearchFields.NAME));
            dataverse.setAffiliation((String) solrDocument.getFieldValue(SearchFields.DATAVERSE_AFFILIATION));
            dataverse.setDescription((String) solrDocument.getFieldValue(SearchFields.DESCRIPTION));
        }
        dataverses.add(dataverse);
    }
    result.setResults(dataverses);
    result.setTotal((int) docs.getNumFound());
    return result;
}

From source file:co.diji.solr.XMLWriter.java

License:Apache License

public final void writeSolrDocumentList(String name, final SolrDocumentList docs, Set<String> fields)
        throws IOException {
    this.writeDocuments(name, new DocumentListInfo() {
        public int getCount() {
            return docs.size();
        }//  w w  w  .  j  a va2  s  .c o m

        public Float getMaxScore() {
            return docs.getMaxScore();
        }

        public long getNumFound() {
            return docs.getNumFound();
        }

        public long getStart() {
            return docs.getStart();
        }

        public void writeDocs(boolean includeScore, Set<String> fields) throws IOException {
            for (SolrDocument doc : docs) {
                writeDoc(null, doc, fields, includeScore);
            }
        }
    }, fields);
}

From source file:com.aboutdata.service.bean.SearchServiceImpl.java

/**
 * ? /*  w  ww  .ja  va2  s . c  om*/
 *
 * @param keyword
 * @param pageable
 * @return
 */
@Override
public Page<PhotosModel> search(String keyword, Pageable pageable) {
    SolrQuery query = new SolrQuery();
    query.setQuery("tags:(" + keyword + ")  OR title:(" + keyword + ")");
    try {
        //?
        query.setStart((pageable.getPageNumber() - 1) * pageable.getPageSize());
        query.setRows(pageable.getPageSize());
        //?
        QueryResponse rsp = solrServer.query(query);
        //?
        SolrDocumentList docs = rsp.getResults();
        List<PhotosModel> models = new ArrayList<PhotosModel>();
        for (SolrDocument solrDocument : docs) {
            String id = solrDocument.getFieldValue("id").toString();
            String title = solrDocument.getFieldValue("title").toString();
            String large = solrDocument.getFieldValue("large").toString();
            String medium = solrDocument.getFieldValue("medium").toString();
            String thumbnail = solrDocument.getFieldValue("thumbnail").toString();
            String source = solrDocument.getFieldValue("source").toString();
            String member_id = solrDocument.getFieldValue("member_id").toString();
            String member_User_name = solrDocument.getFieldValue("member_name").toString();

            //?? ??idusername
            MemberModel member = new MemberModel();
            member.setId(member_id);
            member.setUsername(member_User_name);

            String wallhaven = solrDocument.getFieldValue("wallhaven").toString();
            String create_date = solrDocument.getFieldValue("create_date").toString();
            String modify_date = solrDocument.getFieldValue("modify_date").toString();

            String tags = solrDocument.getFieldValue("tags").toString();

            Set<Tag> tagSet = tagService.getTagsFromString(tags);

            PhotosModel model = new PhotosModel();
            model.setId(id);
            model.setTitle(title);
            model.setLarge(large);
            model.setMedium(medium);
            model.setThumbnail(thumbnail);
            model.setSource(source);

            model.setWallhaven(wallhaven);
            //model.setCreateDate(new Date());
            // model.setModifyDate(new DateTime(modify_date).toDate());

            model.setMember(member);
            //?tag
            List<TagModel> tagList = TagDTO.getTagModelsDTO(tagSet);
            model.setTags(tagList);

            models.add(model);
        }
        Page<PhotosModel> result = new PageImpl<PhotosModel>(models, pageable, docs.getNumFound());
        return result;
    } catch (SolrServerException ex) {
        logger.error("build index error {}", ex);
    }
    return null;
}

From source file:com.bindez.nlp.extract.ngram.corpus.ExtractWord.java

public List<String> query() throws SolrServerException {
    List<String> result = new ArrayList<String>();
    server = new MyanmarCorpusSolrServer().getSolrServer();

    SolrQuery query = new SolrQuery();
    query.setQuery("*:*");
    //query.add("fl","fl:totaltermfreq(content,"+word+")");
    query.setRows(Integer.MAX_VALUE);
    QueryResponse response = server.query(query);
    SolrDocumentList results = response.getResults();
    long numFound = results.getNumFound();
    System.out.println(numFound);
    for (SolrDocument result1 : results) {
        String word = result1.getFieldValue("id").toString();
        result.add(word);//  w w  w .ja v a  2s. c  om

    }

    return result;

}

From source file:com.databasepreservation.visualization.utils.SolrUtils.java

public static <T extends Serializable> IndexResult<T> queryResponseToIndexResult(QueryResponse response,
        Class<T> responseClass, List<String> columnNames, Facets facets) throws GenericException {
    final SolrDocumentList docList = response.getResults();
    final List<FacetFieldResult> facetResults = processFacetFields(facets, response.getFacetFields());
    final long offset = docList.getStart();
    final long limit = docList.size();
    final long totalCount = docList.getNumFound();
    final List<T> docs = new ArrayList<T>();

    for (SolrDocument doc : docList) {
        T result;/*from  w  w  w .  jav  a 2 s. c o  m*/
        result = solrDocumentTo(responseClass, doc);
        docs.add(result);
    }

    return new IndexResult<T>(offset, limit, totalCount, docs, facetResults);
}

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

License:Open Source License

private static void printResults(SolrDocumentList solrDocumentList) {
    System.out.println("numFound:" + solrDocumentList.getNumFound());
    System.out.println("start:" + solrDocumentList.getStart());
    for (SolrDocument solrDocument : solrDocumentList) {
        System.out.println("**************");
        System.out.println("title:" + solrDocument.getFieldValue("title"));
        System.out.println("description:" + solrDocument.getFieldValue("description"));
        System.out.println("link:" + solrDocument.getFieldValue("link"));
    }//www  . ja va 2  s. co m
}

From source file:com.doculibre.constellio.servlets.SolrJExampleMain.java

License:Open Source License

/**
 * Print documents and facets// w w w. ja v  a  2s.c o m
 * 
 * @param response
 */
@SuppressWarnings("unchecked")
public static void print(QueryResponse response) {
    SolrDocumentList docs = response.getResults();
    if (docs != null) {
        System.out.println(docs.getNumFound() + " documents found, " + docs.size() + " returned : ");
        for (int i = 0; i < docs.size(); i++) {
            SolrDocument doc = docs.get(i);
            System.out.println("\t" + doc.toString());
        }
    }

    List<FacetField> fieldFacets = response.getFacetFields();
    if (fieldFacets != null && fieldFacets.isEmpty()) {
        System.out.println("\nField Facets : ");
        for (FacetField fieldFacet : fieldFacets) {
            System.out.print("\t" + fieldFacet.getName() + " :\t");
            if (fieldFacet.getValueCount() > 0) {
                for (Count count : fieldFacet.getValues()) {
                    System.out.print(count.getName() + "[" + count.getCount() + "]\t");
                }
            }
            System.out.println("");
        }
    }

    Map<String, Integer> queryFacets = response.getFacetQuery();
    if (queryFacets != null && !queryFacets.isEmpty()) {
        System.out.println("\nQuery facets : ");
        for (String queryFacet : queryFacets.keySet()) {
            System.out.println("\t" + queryFacet + "\t[" + queryFacets.get(queryFacet) + "]");
        }
        System.out.println("");
    }

    NamedList<NamedList<Object>> spellCheckResponse = (NamedList<NamedList<Object>>) response.getResponse()
            .get("spellcheck");

    if (spellCheckResponse != null) {
        Iterator<Entry<String, NamedList<Object>>> wordsIterator = spellCheckResponse.iterator();

        while (wordsIterator.hasNext()) {
            Entry<String, NamedList<Object>> entry = wordsIterator.next();
            String word = entry.getKey();
            NamedList<Object> spellCheckWordResponse = entry.getValue();
            boolean correct = spellCheckWordResponse.get("frequency").equals(1);
            System.out.println("Word: " + word + ",\tCorrect?: " + correct);
            NamedList<Integer> suggestions = (NamedList<Integer>) spellCheckWordResponse.get("suggestions");
            if (suggestions != null && suggestions.size() > 0) {
                System.out.println("Suggestions : ");
                Iterator<Entry<String, Integer>> suggestionsIterator = suggestions.iterator();
                while (suggestionsIterator.hasNext()) {
                    System.out.println("\t" + suggestionsIterator.next().getKey());
                }

            }
            System.out.println("");
        }

    }

}

From source file:com.doculibre.constellio.utils.NamedListUtils.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Element toElement(Object value) {
    String elementTag = null;//from  w  ww.  j av a 2 s .com
    String strValue = null;
    Element item = null;
    if (value == null) {
        return null;

    } else if (value instanceof NamedList) {
        NamedList<Object> nl = (NamedList<Object>) value;
        item = newNamedListElement(nl);

    } else if (value instanceof Integer) {
        elementTag = "int";

    } else if (value instanceof String) {
        elementTag = "str";

    } else if (value instanceof Date) {
        elementTag = "date";
        SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        dateParser.setTimeZone(TimeZone.getTimeZone("GMT"));
        strValue = dateParser.format(value);

    } else if (value instanceof Boolean) {
        elementTag = "bool";
        strValue = ((Boolean) value) ? "true" : "false";

    } else if (value instanceof Long) {
        elementTag = "long";

    } else if (value instanceof Float) {
        elementTag = "float";

    } else if (value instanceof Double) {
        elementTag = "double";

    } else if (value instanceof SolrDocumentList) {
        SolrDocumentList documentList = (SolrDocumentList) value;
        item = newListElement((List) value);
        // We want the name to be the first attribute (for Junit)
        item.setAttribute("name", "");
        item.setAttribute("numFound", "" + documentList.getNumFound());
        item.setAttribute("start", "" + documentList.getStart());

    } else if (value instanceof List) {
        item = newListElement((List) value);

    } else if (value instanceof SolrDocument) {
        // Only for unit tests
        item = newSolrDocument((SolrDocument) value);
        nameElement(item, "doc");

    } else if (value instanceof Map) {
        item = newMapElement(((SolrDocument) value).getFieldValuesMap());

    } else {
        throw new RuntimeException("UnsupportedType " + value.getClass().getSimpleName());
    }

    if (item == null) {
        item = new Element(elementTag);
        item.setText(strValue != null ? strValue : String.valueOf(value));

    }
    return item;
}

From source file:com.frank.search.solr.core.ResultHelper.java

License:Apache License

static <T> Map<Object, GroupResult<T>> convertGroupQueryResponseToGroupResultMap(Query query,
        Map<String, Object> objectNames, QueryResponse response, SolrTemplate solrTemplate, Class<T> clazz) {

    GroupResponse groupResponse = response.getGroupResponse();
    SolrDocumentList sdl = response.getResults();

    if (groupResponse == null) {
        return Collections.emptyMap();
    }//from w ww  . j a  va 2  s  .  c  o  m

    Map<Object, GroupResult<T>> result = new LinkedHashMap<Object, GroupResult<T>>();

    List<GroupCommand> values = groupResponse.getValues();
    for (GroupCommand groupCommand : values) {

        List<GroupEntry<T>> groupEntries = new ArrayList<GroupEntry<T>>();

        for (Group group : groupCommand.getValues()) {

            SolrDocumentList documentList = group.getResult();
            List<T> beans = solrTemplate.convertSolrDocumentListToBeans(documentList, clazz);
            Page<T> page = new PageImpl<T>(beans, query.getGroupOptions().getPageRequest(),
                    documentList.getNumFound());
            groupEntries.add(new SimpleGroupEntry<T>(group.getGroupValue(), page));
        }

        int matches = groupCommand.getMatches();
        Integer ngroups = groupCommand.getNGroups();
        String name = groupCommand.getName();

        PageImpl<GroupEntry<T>> page;
        if (ngroups != null) {
            page = new PageImpl<GroupEntry<T>>(groupEntries, query.getPageRequest(), ngroups.intValue());
        } else {
            page = new PageImpl<GroupEntry<T>>(groupEntries);
        }

        SimpleGroupResult<T> groupResult = new SimpleGroupResult<T>(matches, ngroups, name, page);
        result.put(name, groupResult);
        if (objectNames.containsKey(name)) {
            result.put(objectNames.get(name), groupResult);
        }
    }

    return result;
}

From source file:com.frank.search.solr.core.SolrTemplate.java

License:Apache License

private <T> SolrResultPage<T> createSolrResultPage(Query query, Class<T> clazz, QueryResponse response,
        Map<String, Object> objectsName) {
    List<T> beans = convertQueryResponseToBeans(response, clazz);
    SolrDocumentList results = response.getResults();
    long numFound = results == null ? 0 : results.getNumFound();
    Float maxScore = results == null ? null : results.getMaxScore();

    Pageable pageRequest = query.getPageRequest();

    SolrResultPage<T> page = new SolrResultPage<T>(beans, pageRequest, numFound, maxScore);

    page.setFieldStatsResults(// w w  w  . j  av  a 2s  .co m
            ResultHelper.convertFieldStatsInfoToFieldStatsResultMap(response.getFieldStatsInfo()));
    page.setGroupResults(
            ResultHelper.convertGroupQueryResponseToGroupResultMap(query, objectsName, response, this, clazz));

    return page;
}