Example usage for org.apache.solr.client.solrj SolrQuery removeFacetField

List of usage examples for org.apache.solr.client.solrj SolrQuery removeFacetField

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj SolrQuery removeFacetField.

Prototype

public boolean removeFacetField(String name) 

Source Link

Document

remove a facet field

Usage

From source file:edu.unc.lib.dl.ui.service.SolrQueryLayerService.java

License:Apache License

public void getChildrenCounts(List<BriefObjectMetadata> resultList, AccessGroupSet accessGroups,
        String countName, String queryAddendum, SolrQuery baseQuery) {
    long startTime = System.currentTimeMillis();
    if (resultList == null || resultList.size() == 0)
        return;//  w w w.ja  v a 2s  .c o m

    String ancestorPathField = solrSettings.getFieldName(SearchFieldKeys.ANCESTOR_PATH.name());
    SolrQuery solrQuery;
    if (baseQuery == null) {
        // Create a base query since we didn't receive one
        solrQuery = new SolrQuery();
        StringBuilder query = new StringBuilder("*:*");
        try {
            // Add access restrictions to query
            addAccessRestrictions(query, accessGroups);
        } catch (AccessRestrictionException e) {
            // If the user doesn't have any access groups, they don't have access to anything, return null.
            LOG.error(e.getMessage());
            return;
        }

        solrQuery.setStart(0);
        solrQuery.setRows(0);

        solrQuery.setQuery(query.toString());
    } else {
        // Starting from a base query
        solrQuery = baseQuery.getCopy();
        // Make sure we aren't returning any normal results
        solrQuery.setRows(0);
        // Remove all facet fields so we are only getting ancestor path
        if (solrQuery.getFacetFields() != null) {
            for (String facetField : solrQuery.getFacetFields()) {
                solrQuery.removeFacetField(facetField);
            }
        }
    }

    if (queryAddendum != null) {
        solrQuery.setQuery(solrQuery.getQuery() + " AND " + queryAddendum);
    }

    solrQuery.setFacet(true);
    solrQuery.setFacetMinCount(1);
    solrQuery.addFacetField(ancestorPathField);

    Integer countPageSize;
    try {
        countPageSize = new Integer(searchSettings.getProperty("search.facet.countPageSize"));
    } catch (NumberFormatException e) {
        countPageSize = 20;
    }

    solrQuery.add("f." + ancestorPathField + ".facet.limit", Integer.toString(Integer.MAX_VALUE));
    // Sort by value rather than count so that earlier tiers will come first in case the result gets cut off
    solrQuery.setFacetSort("index");

    java.util.Map<Integer, StringBuilder> tierQueryMap = new java.util.HashMap<Integer, StringBuilder>();
    java.util.Map<Integer, List<BriefObjectMetadata>> containerMap = new java.util.HashMap<Integer, List<BriefObjectMetadata>>();

    // Pare the list of ids we are searching for and assigning counts to down to just containers
    for (BriefObjectMetadata metadataObject : resultList) {
        if (metadataObject.getPath() != null && metadataObject.getContentModel() != null
                && metadataObject.getContentModel().contains(ContentModelHelper.Model.CONTAINER.toString())) {
            CutoffFacetNode highestTier = metadataObject.getPath().getHighestTierNode();
            StringBuilder tierQuery = tierQueryMap.get(highestTier.getTier());
            List<BriefObjectMetadata> containerObjects = containerMap.get(highestTier.getTier());
            if (tierQuery == null) {
                tierQuery = new StringBuilder();
                tierQueryMap.put(highestTier.getTier(), tierQuery);

                containerObjects = new ArrayList<BriefObjectMetadata>();
                containerMap.put(highestTier.getTier(), containerObjects);
            }

            if (tierQuery.length() == 0) {
                tierQuery.append(ancestorPathField).append(":(");
            } else {
                tierQuery.append(" OR ");
            }

            tierQuery.append(SolrSettings.sanitize(highestTier.getSearchValue())).append(",*");
            containerObjects.add(metadataObject);

            // If there are a lot of results, then do a partial lookup
            if (containerObjects.size() >= countPageSize) {
                tierQuery.append(")");
                this.executeChildrenCounts(tierQuery, containerObjects, solrQuery, countName,
                        highestTier.getTier());
                LOG.info("Partial query done at " + System.currentTimeMillis() + " ("
                        + (System.currentTimeMillis() - startTime) + ")");
                containerMap.remove(highestTier.getTier());
                tierQueryMap.remove(highestTier.getTier());
            }
        }
    }

    Iterator<java.util.Map.Entry<Integer, StringBuilder>> queryIt = tierQueryMap.entrySet().iterator();
    while (queryIt.hasNext()) {
        java.util.Map.Entry<Integer, StringBuilder> tierQueryEntry = queryIt.next();
        tierQueryEntry.getValue().append(')');
        this.executeChildrenCounts(tierQueryEntry.getValue(), containerMap.get(tierQueryEntry.getKey()),
                solrQuery, countName, tierQueryEntry.getKey());
    }
    LOG.info("Child count query done at " + System.currentTimeMillis() + " ("
            + (System.currentTimeMillis() - startTime) + ")");
}

From source file:org.ambraproject.search.service.SolrSearchService.java

License:Apache License

/**
 * Populate facets of the search object.
 *
 * If no search results and hence facets are found remove defined filters and try
 * the search again.  Journals and ArticleType facets will always be the complete list.
 *  /*from  w w w.  ja va 2  s  .c om*/
 *
 * @param searchParameters The search parameters
 * @return a populared SearchResultSinglePage object
 * @throws ApplicationException
 */
public SearchResultSinglePage getFilterData(SearchParameters searchParameters) throws ApplicationException {
    //TODO: This function queries SOLR for the journal and article type list
    //We should migrate this away from config and into a database when it is
    //available

    //Does not impact unformattedQuery field.
    SearchParameters sp = cleanStrings(searchParameters);

    String q = searchParameters.getUnformattedQuery().trim();

    //In this use case, if the query string is empty, we want to get facets for everything
    if (q.length() == 0) {
        q = "*:*";
    }

    if (log.isDebugEnabled()) {
        log.debug("Solr Search performed to get facet data on the unformattedSearch String: " + q);
    }

    //We want a complete set of facet data.  So first, lets get it all
    SolrQuery query = createQuery("*:*", 0, 0, false);

    //Remove facets we don't use in this case
    query.removeFacetField("author_facet");
    query.removeFacetField("editor_facet");
    query.removeFacetField("affiliate_facet");
    //Add the one we do want in this case.
    query.addFacetField("cross_published_journal_key");
    query.setFacetLimit(MAX_FACET_SIZE);

    //Related to JO: http://joborder.plos.org/view.php?id=17480
    //(for now) we don't want to search on Issue Images
    query.addFilterQuery(createFilterNoIssueImageDocuments());

    SearchResultSinglePage preFilterResults = search(query);

    setFilters(query, sp, true);

    query.setQuery(q);

    SearchResultSinglePage results = null;
    try {
        results = search(query);
    } catch (SolrException e) {
        query.setQuery("*:*");
        if (log.isWarnEnabled()) {
            log.warn("Solr Search failed on the unformattedSearch String: { " + query.getQuery()
                    + " } so the query will be re-run using the String *:* to populate the Filters"
                    + " on the Advanced Search page.", e);
        }
    }

    if (results == null || results.getTotalNoOfResults() == 0) {
        //If no results, remove optional filters and try again
        for (String filter : query.getFilterQueries()) {
            if (filter.indexOf(createFilterFullDocuments()) < 0) {
                query.removeFilterQuery(filter);
            }
        }

        results = search(query);

        //If results are STILL empty.  We must return something for subjects.
        //So let's use the global list
        if (results.getTotalNoOfResults() == 0) {
            results.setSubjectFacet(preFilterResults.getSubjectFacet());
        }

        results.setFiltersReset(true);
    }

    //Lets always return ALL values for journals and article types
    //These lists will not be dependant on the user's other
    //selections other then the query
    //However, subjects will be!
    results.setJournalFacet(preFilterResults.getJournalFacet());
    results.setArticleTypeFacet(preFilterResults.getArticleTypeFacet());

    return results;
}

From source file:org.ambraproject.service.search.SolrSearchService.java

License:Apache License

/**
 * Populate facets of the search object.
 * <p/>/* w  w  w.j a va  2 s.  c o m*/
 * If no search results and hence facets are found remove defined filters and try the search again.  Journals will
 * always be the complete list.
 *
 * @param searchParameters The search parameters
 * @return a populared SearchResultSinglePage object
 * @throws ApplicationException
 */
public SearchResultSinglePage getFilterData(SearchParameters searchParameters) throws ApplicationException {
    //TODO: This function queries SOLR for the journal and article type list
    //We should migrate this away from config and into a database when it is
    //available

    //Does not impact unformattedQuery field.
    SearchParameters sp = cleanStrings(searchParameters);

    String q = searchParameters.getUnformattedQuery().trim();

    //In this use case, if the query string is empty, we want to get facets for everything
    if (q.length() == 0) {
        q = "*:*";
    }

    if (log.isDebugEnabled()) {
        log.debug("Solr Search performed to get facet data on the unformattedSearch String: " + q);
    }

    //We want a complete set of facet data.  So first, lets get it all
    SolrQuery query = createQuery("*:*", 0, 0, false);

    //Remove facets we don't use in this case
    query.removeFacetField("author_facet");
    query.removeFacetField("editor_facet");
    query.removeFacetField("affiliate_facet");
    //Add the one we do want in this case.
    query.addFacetField("cross_published_journal_key");
    query.addFacetField("article_type");
    query.setFacetLimit(MAX_FACET_SIZE);

    //Related to JO: http://joborder.plos.org/view.php?id=17480
    //(for now) we don't want to search on Issue Images
    query.addFilterQuery(createFilterNoIssueImageDocuments());

    SearchResultSinglePage preFilterResults = search(query);

    setFilters(query, sp, false, false);

    query.setQuery(q);

    SearchResultSinglePage results = null;
    try {
        results = search(query);
    } catch (SolrException e) {
        query.setQuery("*:*");
        if (log.isWarnEnabled()) {
            log.warn("Solr Search failed on the unformattedSearch String: { " + query.getQuery()
                    + " } so the query will be re-run using the String *:* to populate the Filters"
                    + " on the Advanced Search page.", e);
        }
    }

    if (results == null || results.getTotalNoOfResults() == 0) {
        //If no results, remove optional filters and try again
        for (String filter : query.getFilterQueries()) {
            if (filter.indexOf(createFilterFullDocuments()) < 0) {
                query.removeFilterQuery(filter);
            }
        }

        results = search(query);

        //If results are STILL empty.  We must return something for subjects and article type.
        //So let's use the global list
        if (results.getTotalNoOfResults() == 0) {
            results.setSubjectFacet(preFilterResults.getSubjectFacet());
            results.setArticleTypeFacet(preFilterResults.getArticleTypeFacet());
        }

        results.setFiltersReset(true);
    }

    //Lets always return ALL values for journals
    //These lists will not be dependant on the user's other
    //selections other then the query
    //However, subjects and article type will be!
    results.setJournalFacet(preFilterResults.getJournalFacet());
    results.setArticleTypeFacet(preFilterResults.getArticleTypeFacet());

    return results;
}

From source file:org.ambraproject.service.search.SolrSearchService.java

License:Apache License

/**
 * Executes a search where results are grouped by one of the subject facets in the solr schema.
 *
 * @param facetName the subject facet of interest.  Depending on the application, this should be
 *     either "subject_facet" or "subject_hierarchy".  The first does not include the entire taxonomy
 *     path, while the second does./* www . j a va2 s . c  om*/
 * @param journal journal of interest
 * @return solr server response
 * @throws ApplicationException
 */
private QueryResponse executeSubjectFacetSearch(String facetName, String journal) throws ApplicationException {
    SolrQuery query = createQuery("*:*", 0, 0, false);

    // We don't care about results, just facet counts.
    query.setRows(0);

    // We only care about full documents
    query.addFilterQuery(createFilterFullDocuments());
    query.addFilterQuery(createFilterNoIssueImageDocuments());

    // Remove facets we don't use in this case.
    query.removeFacetField("author_facet");
    query.removeFacetField("editor_facet");
    query.removeFacetField("affiliate_facet");
    query.removeFacetField("subject_facet");
    query.removeFacetField("subject_hierarchy");

    // Add the one we do want.
    query.addFacetField(facetName);

    if (journal != null && journal.length() > 0) {
        query.addFilterQuery("cross_published_journal_key:" + journal);
    }

    query.setFacetLimit(-1); // unlimited
    return getSOLRResponse(query);
}

From source file:org.ambraproject.service.search.SolrSearchService.java

License:Apache License

private SortedMap<String, Long> getTopSubjectsFromSOLR() throws ApplicationException {
    SolrQuery query = createQuery("*:*", 0, 0, false);

    // We don't care about results, just facet counts.
    query.setRows(0);/* w w w. j a va 2 s. co  m*/

    // We only care about full documents
    query.addFilterQuery(createFilterFullDocuments());

    // Remove facets we don't use in this case.
    query.removeFacetField("author_facet");
    query.removeFacetField("editor_facet");
    query.removeFacetField("affiliate_facet");
    query.removeFacetField("subject_facet");

    // Add the one we do want.
    query.addFacetField("subject_level_1");
    query.setFacetLimit(-1); // unlimited

    QueryResponse queryResponse = getSOLRResponse(query);
    FacetField facet = queryResponse.getFacetField("subject_level_1");

    SortedMap<String, Long> results = new TreeMap<String, Long>();

    //If there is no facet.  Should never happen outside a unit test
    if (facet.getValues() == null) {
        log.warn("No subject_level_1 facet");
    } else {
        for (FacetField.Count count : facet.getValues()) {
            results.put(count.getName(), count.getCount());
        }
    }

    return results;
}

From source file:org.mousephenotype.cda.solr.service.GeneService.java

License:Apache License

/**
 * /*w  ww .  j  av a 2  s.c om*/
 * @param geneIds
 * @return Number of genes (from the provided list) in each status of interest.
 */
public HashMap<String, Long> getStatusCount(Set<String> geneIds) {

    HashMap<String, Long> res = new HashMap<>();

    // build query for these genes
    String geneQuery = GeneDTO.MGI_ACCESSION_ID + ":(" + StringUtils.join(geneIds, " OR ").replace(":", "\\:")
            + ")";

    SolrQuery solrQuery = new SolrQuery();
    solrQuery.setQuery(geneQuery).setRows(1).setFacet(true);
    QueryResponse solrResponse;
    try {
        // add facet for latest_project_status 
        solrQuery.addFacetField(GeneDTO.LATEST_ES_CELL_STATUS);
        solrResponse = geneCore.query(solrQuery);
        // put all values in the hash
        for (Count c : solrResponse.getFacetField(GeneDTO.LATEST_ES_CELL_STATUS).getValues()) {
            res.put(c.getName(), c.getCount());
        }

        // add facet latest_es_cell_status
        solrQuery.removeFacetField(GeneDTO.LATEST_ES_CELL_STATUS);
        solrResponse = geneCore.query(solrQuery.addFacetField(GeneDTO.LATEST_PROJECT_STATUS));
        // put all values in the hash
        for (Count c : solrResponse.getFacetField(GeneDTO.LATEST_PROJECT_STATUS).getValues()) {
            res.put(c.getName(), c.getCount());
        }
    } catch (SolrServerException | IOException e) {
        e.printStackTrace();
    }

    return res;
}

From source file:uk.ac.ebi.phenotype.service.GeneService.java

License:Apache License

/**
 * //w  ww . ja  va2 s  .  co m
 * @param geneIds
 * @return Number of genes (from the provided list) in each status of interest.
 */
public HashMap<String, Long> getStatusCount(Set<String> geneIds) {

    HashMap<String, Long> res = new HashMap<>();

    // build query for these genes
    String geneQuery = GeneDTO.MGI_ACCESSION_ID + ":(" + StringUtils.join(geneIds, " OR ").replace(":", "\\:")
            + ")";
    System.out.println("geneQuery: " + geneQuery);
    SolrQuery solrQuery = new SolrQuery();
    solrQuery.setQuery(geneQuery).setRows(1).setFacet(true);
    QueryResponse solrResponse;
    try {
        // add facet for latest_project_status 
        solrQuery.addFacetField(GeneDTO.LATEST_ES_CELL_STATUS);
        System.out.println("---- " + solr.getBaseURL() + "/select?" + solrQuery);
        solrResponse = solr.query(solrQuery);
        // put all values in the hash
        for (Count c : solrResponse.getFacetField(GeneDTO.LATEST_ES_CELL_STATUS).getValues()) {
            res.put(c.getName(), c.getCount());
        }

        // add facet latest_es_cell_status
        solrQuery.removeFacetField(GeneDTO.LATEST_ES_CELL_STATUS);
        solrResponse = solr.query(solrQuery.addFacetField(GeneDTO.LATEST_PROJECT_STATUS));
        // put all values in the hash
        for (Count c : solrResponse.getFacetField(GeneDTO.LATEST_PROJECT_STATUS).getValues()) {
            res.put(c.getName(), c.getCount());
        }
    } catch (SolrServerException e) {
        e.printStackTrace();
    }

    return res;
}