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:org.apache.sentry.tests.e2e.solr.TestSubsetQueryOperations.java

License:Apache License

private void querySimple(String collectionName, QueryRequest request, CloudSolrClient client) throws Exception {
    /*//from  w  w w  .  ja v  a  2s  .  c o m
    subset_user_012  => subset_role0, subset_role1, subset_role2
    subset_user_013  => subset_role0, subset_role1, subset_role3
    subset_user_023  => subset_role0, subset_role2, subset_role3
    subset_user_123  => subset_role1, subset_role2, subset_role3
    subset_user_0    => subset_role0
    subset_user_2    => subset_role2
    subset_user_01   => subset_role0, subset_role1
    subset_user_23   => subset_role2, subset_role3
    subset_user_0123 => subset_role0, subset_role1, subset_role2, subset_role3
    Note: All users have an extra role for good measure. This should not impact the results
     */

    // as junit  -- should only get docs with no labels as allowMissing=true

    int expectedResultMultiplier = (int) (NUM_DOCS / (Math.pow(2, NUM_AUTH_TOKENS)));

    Set<String> roleSet = Sets.newHashSet();
    checkSimpleQueryResults(collectionName, request, client, "subset_user_no", expectedResultMultiplier,
            roleSet);

    setAuthenticationUser("subset_user_no");
    QueryResponse rsp = request.process(client, collectionName);
    SolrDocumentList docList = rsp.getResults();
    assertEquals(expectedResultMultiplier, docList.getNumFound());
    for (SolrDocument doc : docList) {
        String id = doc.getFieldValue("id").toString();
        assertEquals(0, Long.valueOf(id) % 16);
        assertTrue(doc.getFieldValues(AUTH_FIELD) == null || doc.getFieldValues(AUTH_FIELD).isEmpty());
    }

    // as subset_user_1234 - should see all docs
    roleSet = Sets.newHashSet("subset_role0", "subset_role1", "subset_role2", "subset_role3");
    checkSimpleQueryResults(collectionName, request, client, "subset_user_0123", NUM_DOCS, roleSet);

    roleSet = Sets.newHashSet("subset_role0", "subset_role1", "subset_role2");
    checkSimpleQueryResults(collectionName, request, client, "subset_user_012", 8 * expectedResultMultiplier,
            roleSet);

    roleSet = Sets.newHashSet("subset_role0", "subset_role1", "subset_role3");
    checkSimpleQueryResults(collectionName, request, client, "subset_user_013", 8 * expectedResultMultiplier,
            roleSet);

    roleSet = Sets.newHashSet("subset_role0", "subset_role2", "subset_role3");
    checkSimpleQueryResults(collectionName, request, client, "subset_user_023", 8 * expectedResultMultiplier,
            roleSet);

    roleSet = Sets.newHashSet("subset_role1", "subset_role2", "subset_role3");
    checkSimpleQueryResults(collectionName, request, client, "subset_user_123", 8 * expectedResultMultiplier,
            roleSet);

    roleSet = Sets.newHashSet("subset_role0");
    checkSimpleQueryResults(collectionName, request, client, "subset_user_0", 2 * expectedResultMultiplier,
            roleSet);

    roleSet = Sets.newHashSet("subset_role2");
    checkSimpleQueryResults(collectionName, request, client, "subset_user_2", 2 * expectedResultMultiplier,
            roleSet);

    roleSet = Sets.newHashSet("subset_role0", "subset_role1");
    checkSimpleQueryResults(collectionName, request, client, "subset_user_01", 4 * expectedResultMultiplier,
            roleSet);

    roleSet = Sets.newHashSet("subset_role2", "subset_role3");
    checkSimpleQueryResults(collectionName, request, client, "subset_user_23", 4 * expectedResultMultiplier,
            roleSet);

}

From source file:org.apache.sentry.tests.e2e.solr.TestSubsetQueryOperations.java

License:Apache License

private void checkSimpleQueryResults(String collectionName, QueryRequest request, CloudSolrClient client,
        String username, int expectedResults, Set<String> roles) throws Exception {
    setAuthenticationUser(username);//from w w w  . ja va 2  s .  co m
    QueryResponse rsp = request.process(client, collectionName);
    SolrDocumentList docList = rsp.getResults();

    assertEquals(expectedResults, docList.getNumFound());
    for (SolrDocument doc : docList) {
        Collection<Object> fieldValues = doc.getFieldValues(AUTH_FIELD);
        if (fieldValues != null && !fieldValues.isEmpty()) {
            assertTrue(roles.containsAll(fieldValues));
        }
    }
}

From source file:org.apache.sentry.tests.e2e.solr.TestSubsetQueryOperations.java

License:Apache License

private void testAllRolesTokenQueries(String collectionName, boolean allowMissingValues, int junit,
        int allRolesOnly, int noRoles, CloudSolrClient client) throws Exception {
    QueryRequest request = new QueryRequest(new SolrQuery("*:*"));

    setAuthenticationUser("admin");
    QueryResponse rsp = request.process(client, collectionName);
    SolrDocumentList docList = rsp.getResults();

    int expectedResults = allRolesOnly;
    if (allowMissingValues) {
        expectedResults += noRoles;//  w w w . j a va  2s .  c o m
    }

    assertEquals(expectedResults, docList.getNumFound());

    // as junit -- should get junit added + onlyAllRolesAdded
    setAuthenticationUser("junit");
    rsp = request.process(client, collectionName);
    docList = rsp.getResults();

    expectedResults = junit + allRolesOnly;
    if (allowMissingValues) {
        expectedResults += noRoles;
    }

    assertEquals("junit user, with allowMissingValues: " + allowMissingValues, expectedResults,
            docList.getNumFound());
}

From source file:org.codelibs.elasticsearch.solr.solr.XMLWriter.java

License:Apache License

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

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

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

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

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

From source file:org.codelibs.fess.helper.IndexingHelper.java

License:Apache License

protected SolrDocumentList getSolrDocumentList(final SolrGroup solrGroup, final String fq, final String q,
        final String[] fields, final int row) {
    final SolrQuery sq = new SolrQuery();
    if (fq != null) {
        sq.setFilterQueries(fq);/*from w w  w . j  a va  2  s.  c o m*/
    }
    sq.setQuery(q);
    if (fields != null) {
        sq.setFields(fields);
    }
    sq.setRows(row);
    final SolrDocumentList docList = solrGroup.query(sq).getResults();
    if (docList.getNumFound() <= row) {
        return docList;
    }
    return getSolrDocumentList(solrGroup, fq, q, fields, (int) docList.getNumFound());
}

From source file:org.codelibs.fess.helper.IndexingHelper.java

License:Apache License

protected SolrDocumentList getChildSolrDocumentList(final SolrGroup solrGroup, final String id,
        final String[] fields, final int row) {
    final FieldHelper fieldHelper = ComponentUtil.getFieldHelper();
    final SolrQuery solrQuery = new SolrQuery();
    solrQuery.setQuery("{!raw f=" + fieldHelper.parentIdField + " v=\"" + id + "\"}");
    if (fields != null) {
        solrQuery.setFields(fields);//w w w.j a v a2 s. c  om
    }
    solrQuery.setRows(row);
    final SolrDocumentList docList = solrGroup.query(solrQuery).getResults();
    if (docList.getNumFound() <= row) {
        return docList;
    }
    return getChildSolrDocumentList(solrGroup, id, fields, (int) docList.getNumFound());
}

From source file:org.codelibs.fess.util.QueryResponseList.java

License:Apache License

public void init(final QueryResponse queryResponse, final int pageSize) {
    long start = 0;
    long numFound = 0;
    if (queryResponse != null) {
        final SolrDocumentList sdList = queryResponse.getResults();
        start = sdList.getStart();/*w ww.  ja  va 2s . com*/
        numFound = sdList.getNumFound();
        queryTime = queryResponse.getQTime();
        searchTime = queryResponse.getElapsedTime();

        final Object partialResultsValue = queryResponse.getResponseHeader().get(PARTIAL_RESULTS);
        if (partialResultsValue != null && ((Boolean) partialResultsValue).booleanValue()) {
            partialResults = true;
        }

        // build highlighting fields
        final QueryHelper queryHelper = ComponentUtil.getQueryHelper();
        final FieldHelper fieldHelper = ComponentUtil.getFieldHelper();
        final String hlPrefix = queryHelper.getHighlightingPrefix();
        for (final SolrDocument solrDocMap : sdList) {
            final Map<String, Object> docMap = new HashMap<String, Object>();
            docMap.putAll(solrDocMap);

            try {
                final Object idValue = docMap.get(fieldHelper.idField);
                if (queryResponse.getHighlighting().get(idValue) != null) {
                    for (final String hf : queryHelper.getHighlightingFields()) {
                        final List<String> highlightSnippets = queryResponse.getHighlighting().get(idValue)
                                .get(hf);
                        String value = null;
                        if (highlightSnippets != null && !highlightSnippets.isEmpty()) {
                            value = StringUtils.join(highlightSnippets, "...");
                            docMap.put(hlPrefix + hf, value);
                        }
                    }
                }
            } catch (final Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Could not create a highlighting value: " + docMap, e);
                }
            }

            // ContentTitle
            final ViewHelper viewHelper = ComponentUtil.getViewHelper();
            if (viewHelper != null) {
                docMap.put("contentTitle", viewHelper.getContentTitle(docMap));
                docMap.put("contentDescription", viewHelper.getContentDescription(docMap));
                docMap.put("urlLink", viewHelper.getUrlLink(docMap));
                docMap.put("sitePath", viewHelper.getSitePath(docMap));
            }

            parent.add(docMap);
        }

        // facet
        final List<FacetField> facetFields = queryResponse.getFacetFields();
        final Map<String, Integer> facetQueryMap = queryResponse.getFacetQuery();
        if (facetFields != null || facetQueryMap != null) {
            facetResponse = new FacetResponse(facetFields, facetQueryMap);
        }

        // mlt
        final Object moreLikeThisMap = queryResponse.getResponse().get(MORE_LIKE_THIS);
        if (moreLikeThisMap instanceof SimpleOrderedMap) {
            moreLikeThisResponse = new MoreLikeThisResponse();
            final int size = ((SimpleOrderedMap<?>) moreLikeThisMap).size();
            for (int i = 0; i < size; i++) {
                final String id = ((SimpleOrderedMap<?>) moreLikeThisMap).getName(i);
                final Object docList = ((SimpleOrderedMap<?>) moreLikeThisMap).getVal(i);
                if (StringUtil.isNotBlank(id) && docList instanceof SolrDocumentList) {
                    final List<Map<String, Object>> docMapList = new ArrayList<Map<String, Object>>(
                            ((SolrDocumentList) docList).size());
                    for (final SolrDocument solrDoc : (SolrDocumentList) docList) {
                        final Map<String, Object> docMap = new HashMap<String, Object>();
                        docMap.putAll(solrDoc);
                        docMapList.add(docMap);
                    }
                    moreLikeThisResponse.put(id, docMapList);
                }
            }
        }

        // docValues
        final Object docValuesObj = queryResponse.getResponse().get(DOC_VALUES);
        if (docValuesObj instanceof SimpleOrderedMap) {
            @SuppressWarnings("unchecked")
            final SimpleOrderedMap<List<Long>> docValuesMap = (SimpleOrderedMap<List<Long>>) docValuesObj;
            for (int i = 0; i < docValuesMap.size(); i++) {
                final String name = docValuesMap.getName(i);
                final List<Long> valueList = docValuesMap.getVal(i);
                for (int j = 0; j < valueList.size() && j < parent.size(); j++) {
                    parent.get(j).put(name, valueList.get(j));
                }
            }
        }
    }
    calculatePageInfo(start, pageSize, numFound);
}

From source file:org.craftercms.commerce.client.itest.ProductServiceTest.java

License:Open Source License

@Test
public void testSave() throws Exception {

    String id = "product-2003";
    Date now = new Date();
    String creator = "Spiderman";
    String modifier = "The Hulk";
    long numFound;

    SolrQuery solrQuery = new SolrQuery(BaseType.SOLR_ID_FIELD + ":" + id);
    solrQuery.setRows(1);/*from  w w w  .  j  a  v a 2s.c  o m*/

    numFound = solrServer.query(solrQuery).getResults().getNumFound();
    Assert.assertEquals(0, numFound);

    Product product = new Product();
    product.setId(id);
    product.setCreationDate(now);
    product.setCreatedBy(creator);
    product.setLastModifiedBy(modifier);
    ServiceResponse<Product> response = productService().save(product);
    Assert.assertEquals(true, response.isSuccess());

    SolrDocumentList solrDocList = solrServer.query(solrQuery).getResults();
    Assert.assertEquals(1, solrDocList.getNumFound());
    Assert.assertEquals(1, solrDocList.size());

    SolrDocument solrDoc = solrDocList.get(0);
    Assert.assertEquals(id, solrDoc.getFieldValue(BaseType.SOLR_ID_FIELD));
    Assert.assertEquals(now, solrDoc.getFieldValue(BaseType.SOLR_CREATION_DATE_FIELD));
    Assert.assertEquals(creator, solrDoc.getFieldValue(BaseType.SOLR_CREATED_BY_ID_FIELD));
    Assert.assertEquals(modifier, solrDoc.getFieldValue(BaseType.SOLR_LAST_MODIFIED_BY_ID_FIELD));

}

From source file:org.craftercms.search.service.impl.SolrSearchService.java

License:Open Source License

@SuppressWarnings("unchecked")
protected Object toSerializableValue(Object namedListValue) {
    if (namedListValue instanceof NamedList) {
        // The value can also be a NamedList, so convert it to map.
        return toMap((NamedList<Object>) namedListValue);
    } else if (namedListValue instanceof SolrDocumentList) {
        // If the value is a SolrDocumentList, copy the list attributes to a map
        SolrDocumentList docList = (SolrDocumentList) namedListValue;
        Map<String, Object> docListMap = new HashMap<String, Object>(4);

        docListMap.put(DOCUMENT_LIST_START_PROPERTY_NAME, docList.getStart());
        docListMap.put(DOCUMENT_LIST_NUM_FOUND_PROPERTY_NAME, docList.getNumFound());
        docListMap.put(DOCUMENT_LIST_MAX_SCORE_PROPERTY_NAME, docList.getMaxScore());
        docListMap.put(DOCUMENT_LIST_DOCUMENTS_PROPERTY_NAME, extractDocs(docList));

        return docListMap;
    } else {/*ww w  . j a  v a2 s  .  c  o  m*/
        return namedListValue;
    }
}

From source file:org.dataconservancy.dcs.access.impl.solr.DcsSolrIndex.java

License:Apache License

public SearchResult search(String query, int offset, int maxmatches, String... params) throws IOException {
    if (offset < 0) {
        throw new IllegalArgumentException("offset < 0");
    }/*w  w w  .  j a  v a2 s  .  c  o  m*/

    if ((params.length & 1) > 0) {
        throw new IllegalArgumentException("parameter name without value");
    }

    if (maxmatches <= 0 || maxmatches > MAX_MATCHES) {
        maxmatches = MAX_MATCHES;
    }

    try {
        QueryResponse resp = searcher.search(query, offset, maxmatches, params);
        SolrDocumentList docs = resp.getResults();
        SearchResult result = new SearchResult(offset, docs.getNumFound());

        for (SolrDocument doc : docs) {
            DcsEntity entity = DcsSolrMapper.fromSolr(doc);
            String context = null;

            if (resp.getHighlighting() != null) {
                Map<String, List<String>> snippets = resp.getHighlighting().get(entity.getId());

                // TODO context format?

                if (snippets != null) {
                    StringBuilder sb = new StringBuilder();

                    for (String field : snippets.keySet()) {
                        sb.append(field + ": '" + snippets.get(field) + "' ");
                    }

                    context = sb.toString();
                }
            }

            result.getMatches().add(new Match(entity, context));
        }

        return result;
    } catch (SolrException e) {
        throw new IOException(e);
    } catch (SolrServerException e) {
        throw new IOException(e);
    }
}