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

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

Introduction

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

Prototype

public SolrQuery setFacetLimit(int lim) 

Source Link

Document

set the facet limit

Usage

From source file:org.ofbiz.solr.SolrProductSearch.java

License:Apache License

/**
 * Runs a query on the Solr Search Engine and returns the results.
 * <p>/* ww  w  . j  a  v a 2  s . c  om*/
 * This function only returns an object of type QueryResponse, so it is probably not a good idea to call it directly from within the
 * groovy files (As a decent example on how to use it, however, use keywordSearch instead).
 */
public static Map<String, Object> runSolrQuery(DispatchContext dctx, Map<String, Object> context) {
    // get Connection
    HttpSolrServer server = null;
    Map<String, Object> result;

    Integer viewIndex = (Integer) context.get("viewIndex");
    Integer viewSize = (Integer) context.get("viewSize");
    if (viewIndex < 1) {
        viewIndex = 1;
    }
    try {
        server = new HttpSolrServer(SolrUtil.solrUrl);
        // create Query Object
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setQuery((String) context.get("query"));
        // solrQuery.setQueryType("dismax");
        boolean faceted = (Boolean) context.get("facet");
        if (faceted) {
            solrQuery.setFacet(faceted);
            //solrQuery.addFacetField("manu");
            solrQuery.addFacetField("features");
            solrQuery.addFacetField("cat");
            solrQuery.setFacetMinCount(1);
            solrQuery.setFacetLimit(8);

            solrQuery.addFacetQuery("listPrice:[0 TO 50]");
            solrQuery.addFacetQuery("listPrice:[50 TO 100]");
            solrQuery.addFacetQuery("listPrice:[100 TO 250]");
            solrQuery.addFacetQuery("listPrice:[250 TO 500]");
            solrQuery.addFacetQuery("listPrice:[500 TO 1000]");
            solrQuery.addFacetQuery("listPrice:[1000 TO 2500]");
            solrQuery.addFacetQuery("listPrice:[2500 TO 5000]");
            solrQuery.addFacetQuery("listPrice:[5000 TO 10000]");
            solrQuery.addFacetQuery("listPrice:[10000 TO 50000]");
            solrQuery.addFacetQuery("listPrice:[50000 TO *]");
        }

        boolean spellCheck = (Boolean) context.get("spellcheck");
        if (spellCheck) {
            solrQuery.setParam("spellcheck", spellCheck);
        }

        boolean highLight = (Boolean) context.get("highlight");
        if (highLight) {
            solrQuery.setHighlight(highLight);
            solrQuery.setHighlightSimplePre("<span class=\"highlight\">");
            solrQuery.addHighlightField("description");
            solrQuery.setHighlightSimplePost("</span>");
            solrQuery.setHighlightSnippets(2);
        }

        // Set additional Parameter
        // SolrQuery.ORDER order = SolrQuery.ORDER.desc;

        if (viewIndex != null && viewIndex > 0) {
            solrQuery.setStart((viewIndex - 1) * viewSize);
        }
        if (viewSize != null && viewSize > 0) {
            solrQuery.setRows(viewSize);
        }

        // if ((List) context.get("queryFilter") != null && ((ArrayList<SolrDocument>) context.get("queryFilter")).size() > 0) {
        // List filter = (List) context.get("queryFilter");
        // String[] tn = new String[filter.size()];
        // Iterator it = filter.iterator();
        // for (int i = 0; i < filter.size(); i++) {
        // tn[i] = (String) filter.get(i);
        // }
        // solrQuery.setFilterQueries(tn);
        // }
        String queryFilter = (String) context.get("queryFilter");
        if (UtilValidate.isNotEmpty(queryFilter))
            solrQuery.setFilterQueries(queryFilter.split(" "));
        if ((String) context.get("returnFields") != null) {
            solrQuery.setFields((String) context.get("returnFields"));
        }

        // if((Boolean)context.get("sortByReverse"))order.reverse();
        if ((String) context.get("sortBy") != null && ((String) context.get("sortBy")).length() > 0) {
            SolrQuery.ORDER order;
            if (!((Boolean) context.get("sortByReverse")))
                order = SolrQuery.ORDER.asc;
            else
                order = SolrQuery.ORDER.desc;
            solrQuery.setSort(((String) context.get("sortBy")).replaceFirst("-", ""), order);
        }

        if ((String) context.get("facetQuery") != null) {
            solrQuery.addFacetQuery((String) context.get("facetQuery"));
        }

        QueryResponse rsp = server.query(solrQuery);
        result = ServiceUtil.returnSuccess();
        result.put("queryResult", rsp);
    } catch (Exception e) {
        Debug.logError(e, e.getMessage(), module);
        result = ServiceUtil.returnError(e.toString());
    }
    return result;
}

From source file:org.ofbiz.solr.SolrUtil.java

License:Apache License

public static Map<String, Object> categoriesAvailable(String catalogId, String categoryId, String productId,
        String facetPrefix, boolean displayproducts, int viewIndex, int viewSize) {
    // create the data model
    Map<String, Object> result = FastMap.newInstance();
    HttpSolrServer server = null;/*from   w ww.  j  av  a  2 s  .  co m*/
    QueryResponse returnMap = new QueryResponse();
    try {
        // do the basic query
        server = new HttpSolrServer(solrUrl);
        // create Query Object
        String query = "inStock[1 TO *]";
        if (categoryId != null)
            query += " +cat:" + categoryId;
        else if (productId != null)
            query += " +productId:" + productId;
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setQuery(query);

        if (catalogId != null)
            solrQuery.setFilterQueries("catalog:" + catalogId);
        if (displayproducts) {
            if (viewSize > -1) {
                solrQuery.setRows(viewSize);
            } else
                solrQuery.setRows(50000);
            if (viewIndex > -1) {
                solrQuery.setStart(viewIndex);
            }
        } else {
            solrQuery.setFields("cat");
            solrQuery.setRows(0);
        }

        if (UtilValidate.isNotEmpty(facetPrefix)) {
            solrQuery.setFacetPrefix(facetPrefix);
        }

        solrQuery.setFacetMinCount(0);
        solrQuery.setFacet(true);
        solrQuery.addFacetField("cat");
        solrQuery.setFacetLimit(-1);
        Debug.logVerbose("solr: solrQuery: " + solrQuery, module);
        returnMap = server.query(solrQuery, METHOD.POST);
        result.put("rows", returnMap);
        result.put("numFound", returnMap.getResults().getNumFound());
    } catch (Exception e) {
        Debug.logError(e.getMessage(), module);
    }
    return result;
}

From source file:org.opencommercesearch.AbstractSearchServer.java

License:Apache License

@Override
public Facet getFacet(Site site, Locale locale, String fieldFacet, int facetLimit, int depthLimit,
        String separator, FilterQuery... filterQueries) throws SearchServerException {
    try {/*www.j ava 2  s . c  o  m*/
        SolrQuery query = new SolrQuery();
        query.setRows(0);
        query.setQuery("*:*");
        query.addFacetField(fieldFacet);
        query.setFacetLimit(facetLimit);
        query.setFacetMinCount(1);
        query.addFilterQuery("country:" + locale.getCountry());

        RepositoryItem catalog = (RepositoryItem) site.getPropertyValue("defaultCatalog");
        String catalogId = catalog.getRepositoryId();
        query.setFacetPrefix(CATEGORY_PATH, catalogId + ".");
        query.addFilterQuery(CATEGORY_PATH + ":" + catalogId);

        if (filterQueries != null) {
            for (FilterQuery filterQuery : filterQueries) {
                query.addFilterQuery(filterQuery.toString());
            }
        }

        QueryResponse queryResponse = getCatalogSolrServer(locale).query(query);
        Facet facet = null;
        if (queryResponse != null && queryResponse.getFacetFields() != null) {
            FacetField facetField = queryResponse.getFacetField(fieldFacet);
            if (facetField != null) {
                List<Count> values = facetField.getValues();
                if (values != null && !values.isEmpty()) {
                    facet = new Facet();
                    facet.setName(StringUtils.capitalize(fieldFacet));
                    List<Filter> filters = new ArrayList<Facet.Filter>();

                    boolean filterByDepth = depthLimit > 0 && StringUtils.isNotBlank(separator);
                    for (Count count : values) {

                        if (filterByDepth
                                && StringUtils.countMatches(count.getName(), separator) > depthLimit) {
                            continue;
                        }

                        Filter filter = new Filter();
                        filter.setName(count.getName());
                        filter.setCount(count.getCount());
                        filter.setFilterQuery(count.getAsFilterQuery());
                        filter.setFilterQueries(count.getAsFilterQuery());
                        filters.add(filter);
                    }
                    facet.setFilters(filters);
                }
            }
        }
        return facet;
    } catch (SolrServerException ex) {
        throw create(SEARCH_EXCEPTION, ex);
    } catch (SolrException ex) {
        throw create(SEARCH_EXCEPTION, ex);
    }
}

From source file:org.pentaho.di.trans.steps.solrinput.SolrInput.java

License:Apache License

/**
 * Once the transformation starts executing, the processRow() method is called repeatedly
 * by PDI for as long as it returns true. To indicate that a step has finished processing rows
 * this method must call setOutputDone() and return false;
 * /*www .j a  v  a  2 s.  c  o m*/
 * Steps which process incoming rows typically call getRow() to read a single row from the
 * input stream, change or add row content, call putRow() to pass the changed row on 
 * and return true. If getRow() returns null, no more rows are expected to come in, 
 * and the processRow() implementation calls setOutputDone() and returns false to
 * indicate that it is done too.
 * 
 * Steps which generate rows typically construct a new row Object[] using a call to
 * RowDataUtil.allocateRowData(numberOfFields), add row content, and call putRow() to
 * pass the new row on. Above process may happen in a loop to generate multiple rows,
 * at the end of which processRow() would call setOutputDone() and return false;
 * 
 * @param smi the step meta interface containing the step settings
 * @param sdi the step data interface that should be used to store
 * 
 * @return true to indicate that the function should be called again, false if the step is done
 */
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {

    if (first) {
        first = false;
        // Create the output row meta-data
        data.outputRowMeta = new RowMeta();
        meta.getFields(data.outputRowMeta, getStepname(), null, null, this, repository, metaStore);
        // For String to <type> conversions, we allocate a conversion meta data row as well...
        data.convertRowMeta = data.outputRowMeta.cloneToType(ValueMetaInterface.TYPE_STRING);

        // get real values
        boolean tryCursor = true;
        Integer startRecord = 0;
        Integer chunkRowSize = 20;
        String realURL = meta.getURL();
        String realQ = meta.getQ();
        String realSort = meta.getSort();
        String realCursor = meta.getCursor();
        String realFq = meta.getFq();
        String realFl = meta.getFl();
        String realFacetQuery = meta.getFacetQuery();
        String realFacetField = meta.getFacetField();
        /* Send and Get the report */
        SolrQuery query = new SolrQuery();
        query.set("rows", chunkRowSize);
        if (realQ != null && !realQ.equals("")) {
            query.set("q", realQ);
        }
        if (realSort != null && !realSort.equals("")) {
            query.set("sort", realSort);
        } else {
            tryCursor = false;
        }
        if (realCursor != null && !realCursor.equals("")) {
            if (realCursor.equals("No")) {
                tryCursor = false;
            }
        }
        if (realFl != null && !realFl.equals("")) {
            query.set("fl", realFl);
        }
        if (realFq != null && !realFq.equals("")) {
            query.set("fq", realFq);
        }
        if (realFacetField != null && !realFacetField.equals("")) {
            //TODO incorporate multiple facet fields at once
            //String[] facetFields = realFacetField.split("\\s*,\\s*");
            //for(int i =0; i < facetFields.length; i++){
            query.addFacetField(realFacetField);
            //}
            query.setFacet(true);
            query.setFacetLimit(-1);
            query.setFacetMinCount(0);
            query.setFacetSort("count");
            query.set("rows", 0);
            tryCursor = false;
            data.facetRequested = true;
        }
        if (realFacetQuery != null && !realFacetQuery.equals("")) {
            query.addFacetQuery(realFacetQuery);
        }
        // You can't use "TimeAllowed" with "CursorMark"
        // The documentation says "Values <= 0 mean 
        // no time restriction", so setting to 0.
        query.setTimeAllowed(0);
        HttpSolrServer solr = new HttpSolrServer(realURL);
        String cursorMark = CursorMarkParams.CURSOR_MARK_START;
        boolean done = false;
        QueryResponse rsp = null;
        while (!done) {
            if (tryCursor) {
                query.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark);
            } else {
                query.setStart(startRecord);
            }
            try {
                rsp = solr.query(query);
            } catch (SolrServerException e) {
                e.printStackTrace();
            }
            if (data.facetRequested) {
                data.facetCountName = rsp.getFacetFields().get(0).getName();
                data.facetCounts = rsp.getFacetFields().get(0).getValues();
                done = true;
            } else {
                SolrDocumentList theseDocs = rsp.getResults();
                for (SolrDocument doc : theseDocs) {
                    data.documentList.add(doc);
                }
            }
            if (tryCursor) {
                String nextCursorMark = rsp.getNextCursorMark();
                if (cursorMark.equals(nextCursorMark)) {
                    done = true;
                } else {
                    cursorMark = nextCursorMark;
                }
            } else {
                startRecord = startRecord + chunkRowSize;
                if (startRecord >= rsp.getResults().getNumFound()) {
                    done = true;
                }
            }
        }
    }

    Object[] outputRowData = null;

    try {
        if (data.facetRequested) {
            // get one row if we can
            if (data.facetCounts.size() - 1 < data.recordIndex) {
                setOutputDone();
                return false;
            }
            FacetField.Count facetRecord = data.facetCounts.get(data.recordIndex);
            outputRowData = prepareFacetRecord(facetRecord);
        } else {
            // get one row if we can
            if (data.documentList.size() - 1 < data.recordIndex) {
                setOutputDone();
                return false;
            }
            SolrDocument record = data.documentList.get(data.recordIndex);
            outputRowData = prepareRecord(record);
        }
        putRow(data.outputRowMeta, outputRowData); // copy row to output rowset(s);
        data.recordIndex++;
        return true;
    } catch (KettleException e) {
        boolean sendToErrorRow = false;
        String errorMessage = null;
        if (getStepMeta().isDoingErrorHandling()) {
            sendToErrorRow = true;
            errorMessage = e.toString();
        } else {
            logError(BaseMessages.getString(PKG, "SolrInput.log.Exception", e.getMessage()));
            logError(Const.getStackTracker(e));
            setErrors(1);
            stopAll();
            setOutputDone(); // signal end to receiver(s)
            return false;
        }
        if (sendToErrorRow) {
            // Simply add this row to the error row
            putError(getInputRowMeta(), outputRowData, 1, errorMessage, null, "SolrInput001");
        }
    }
    return true;
}

From source file:org.pentaho.di.ui.trans.steps.solrinput.SolrInputDialog.java

License:Apache License

private void getFields() {

    try {//from ww w . ja  v  a 2s.c o m
        SolrInputMeta meta = new SolrInputMeta();
        getInfo(meta);
        // clear the current fields grid
        wFields.removeAll();
        // get real values
        boolean tryCursor = true;
        boolean facetRequested = false;
        Integer startRecord = 0;
        Integer chunkRowSize = 20;
        String realURL = transMeta.environmentSubstitute(meta.getURL());
        String realQ = transMeta.environmentSubstitute(meta.getQ());
        String realSort = transMeta.environmentSubstitute(meta.getSort());
        String realCursor = transMeta.environmentSubstitute(meta.getCursor());
        String realFq = transMeta.environmentSubstitute(meta.getFq());
        String realFl = transMeta.environmentSubstitute(meta.getFl());
        String realFacetQuery = transMeta.environmentSubstitute(meta.getFacetQuery());
        String realFacetField = transMeta.environmentSubstitute(meta.getFacetField());
        /* Send and Get the report */
        SolrQuery query = new SolrQuery();
        query.set("rows", chunkRowSize);
        if (realQ != null && !realQ.equals("")) {
            query.set("q", realQ);
        }
        if (realSort != null && !realSort.equals("")) {
            query.set("sort", realSort);
        } else {
            tryCursor = false;
        }
        if (realCursor != null && !realCursor.equals("")) {
            if (realCursor.equals("No")) {
                tryCursor = false;
            }
        }
        if (realFl != null && !realFl.equals("")) {
            query.set("fl", realFl);
        }
        if (realFq != null && !realFq.equals("")) {
            query.set("fq", realFq);
        }
        if (realFacetField != null && !realFacetField.equals("")) {
            //TODO incorporate multiple facet fields at once
            //String[] facetFields = realFacetField.split("\\s*,\\s*");
            //for(int i =0; i < facetFields.length; i++){
            query.addFacetField(realFacetField);
            //}
            query.setFacet(true);
            query.setFacetLimit(-1);
            query.setFacetMinCount(0);
            query.setFacetSort("count");
            query.set("rows", 0);
            tryCursor = false;
            facetRequested = true;
        }
        if (realFacetQuery != null && !realFacetQuery.equals("")) {
            query.addFacetQuery(realFacetQuery);
        }
        // You can't use "TimeAllowed" with "CursorMark"
        // The documentation says "Values <= 0 mean 
        // no time restriction", so setting to 0.
        query.setTimeAllowed(0);
        HttpSolrServer solr = new HttpSolrServer(realURL);
        String cursorMark = CursorMarkParams.CURSOR_MARK_START;
        boolean done = false;
        List<String> headerNames = new ArrayList<String>();
        QueryResponse rsp = null;
        while (!done) {
            if (tryCursor) {
                query.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark);
            } else {
                query.setStart(startRecord);
            }
            try {
                rsp = solr.query(query);
            } catch (SolrServerException e) {
                e.printStackTrace();
            }
            if (facetRequested) {
                headerNames.add(rsp.getFacetFields().get(0).getName());
                headerNames.add("count");
                done = true;
            } else {
                SolrDocumentList docs = rsp.getResults();
                for (SolrDocument doc : docs) {
                    Collection<String> thisNamesArray = doc.getFieldNames();
                    String[] a = thisNamesArray.toArray(new String[thisNamesArray.size()]);
                    for (int j = 0; j < a.length; j++) {
                        if (!headerNames.contains(a[j])) {
                            headerNames.add(a[j]);
                        }
                    }
                }
            }
            if (tryCursor) {
                String nextCursorMark = rsp.getNextCursorMark();
                if (cursorMark.equals(nextCursorMark)) {
                    done = true;
                } else {
                    cursorMark = nextCursorMark;
                }
            } else {
                startRecord = startRecord + chunkRowSize;
                if (startRecord >= rsp.getResults().getNumFound()) {
                    done = true;
                }
            }
        }
        getTableView().table.setItemCount(headerNames.size());
        for (int j = 0; j < headerNames.size(); j++) {
            TableItem item = getTableView().table.getItem(j);
            item.setText(1, headerNames.get(j));
        }
        wFields.removeEmptyRows();
        wFields.setRowNums();
        wFields.optWidth(true);
        getInput().setChanged();
    } catch (Exception e) {
        new ErrorDialog(shell, BaseMessages.getString(PKG, "SolrInputMeta.ErrorRetrieveData.DialogTitle"),
                BaseMessages.getString(PKG, "SolrInputMeta.ErrorRetrieveData.DialogMessage"), e);
    }
}

From source file:org.rsc.liferay.solr.SolrIndexSearcher.java

License:Open Source License

protected Hits doSearch(SearchContext searchContext, Query query) throws Exception {

    SolrQuery solrQuery = translateQuery(searchContext.getCompanyId(), query, searchContext.getSorts(),
            searchContext.getStart(), searchContext.getEnd());

    Map<String, Facet> facets = searchContext.getFacets();

    for (Facet facet : facets.values()) {
        if (facet.isStatic()) {
            continue;
        }/*www.  j  a  v  a  2  s  .  c  om*/

        FacetConfiguration facetConfiguration = facet.getFacetConfiguration();

        if (facet instanceof RangeFacet) {
            solrQuery.addFacetField(facetConfiguration.getFieldName());

            JSONObject dataJSONObject = facetConfiguration.getData();

            JSONArray rangesJSONArray = dataJSONObject.getJSONArray("ranges");

            if (rangesJSONArray == null) {
                continue;
            }

            for (int i = 0; i < rangesJSONArray.length(); i++) {
                JSONObject rangeJSONObject = rangesJSONArray.getJSONObject(i);

                String range = rangeJSONObject.getString("range");

                String facetQuery = facetConfiguration.getFieldName() + StringPool.COLON + range;

                solrQuery.addFacetQuery(facetQuery);
            }
        } else {
            solrQuery.addFacetField(facetConfiguration.getFieldName());
        }

        String facetSort = FacetParams.FACET_SORT_COUNT;

        String order = facetConfiguration.getOrder();

        if (order.equals("OrderValueAsc")) {
            facetSort = FacetParams.FACET_SORT_INDEX;
        }

        solrQuery.add("f." + facetConfiguration.getFieldName() + ".facet.sort", facetSort);
    }

    solrQuery.setFacetLimit(-1);

    QueryResponse queryResponse = _solrServer.query(solrQuery, METHOD.POST);

    boolean allResults = false;

    if (solrQuery.getRows() == 0) {
        allResults = true;
    }

    List<FacetField> facetFields = queryResponse.getFacetFields();

    if (facetFields != null) {
        for (FacetField facetField : facetFields) {
            Facet facet = facets.get(facetField.getName());

            FacetCollector facetCollector = null;

            if (facet instanceof RangeFacet) {
                facetCollector = new SolrFacetQueryCollector(facetField.getName(),
                        queryResponse.getFacetQuery());
            } else {
                facetCollector = new SolrFacetFieldCollector(facetField.getName(), facetField);
            }

            facet.setFacetCollector(facetCollector);
        }
    }

    return subset(solrQuery, query, query.getQueryConfig(), queryResponse, allResults);
}

From source file:org.springframework.data.solr.core.DefaultQueryParser.java

License:Apache License

private boolean enableFaceting(SolrQuery solrQuery, FacetQuery query) {
    FacetOptions facetOptions = query.getFacetOptions();
    if (facetOptions == null || (!facetOptions.hasFields() && !facetOptions.hasFacetQueries()
            && !facetOptions.hasPivotFields())) {
        return false;
    }/*from w ww. j  a va2  s  .c  o m*/
    solrQuery.setFacet(true);
    solrQuery.setFacetMinCount(facetOptions.getFacetMinCount());
    solrQuery.setFacetLimit(facetOptions.getPageable().getPageSize());
    if (facetOptions.getPageable().getPageNumber() > 0) {
        int offset = Math.max(0, facetOptions.getPageable().getOffset());
        solrQuery.set(FacetParams.FACET_OFFSET, offset);
    }
    if (FacetOptions.FacetSort.INDEX.equals(facetOptions.getFacetSort())) {
        solrQuery.setFacetSort(FacetParams.FACET_SORT_INDEX);
    }
    return true;
}

From source file:org.wso2.carbon.registry.indexing.solr.SolrClient.java

License:Open Source License

private String addFacetFields(Map<String, String> fields, SolrQuery query) {
    //set the facet true to enable facet
    //Need to set the Facet to true to enable Facet Query.
    query.setFacet(true);//from ww  w. j  a  v a2  s.c  om
    String fieldName = fields.get(IndexingConstants.FACET_FIELD_NAME);
    String queryField = null;
    if (fieldName != null) {
        //set the field for the facet
        if (IndexingConstants.FIELD_TAGS.equals(fieldName) || IndexingConstants.FIELD_COMMENTS.equals(fieldName)
                || IndexingConstants.FIELD_ASSOCIATION_DESTINATIONS.equals(fieldName)
                || IndexingConstants.FIELD_ASSOCIATION_TYPES.equals(fieldName)) {
            queryField = fieldName + SolrConstants.SOLR_MULTIVALUED_STRING_FIELD_KEY_SUFFIX;
            query.addFacetField(queryField);
        } else {
            queryField = fieldName + SolrConstants.SOLR_STRING_FIELD_KEY_SUFFIX;
            query.addFacetField(queryField);
        }
        //remove the facet field avoid affecting to query results
        fields.remove(IndexingConstants.FACET_FIELD_NAME);
        //set the limit for the facet
        if (fields.get(IndexingConstants.FACET_LIMIT) != null) {
            query.setFacetLimit(Integer.parseInt(fields.get(IndexingConstants.FACET_LIMIT)));
            fields.remove(IndexingConstants.FACET_LIMIT);
        } else {
            query.setFacetLimit(IndexingConstants.FACET_LIMIT_DEFAULT);
        }
        //set the min count for the facet
        if (fields.get(IndexingConstants.FACET_MIN_COUNT) != null) {
            query.setFacetMinCount(Integer.parseInt(fields.get(IndexingConstants.FACET_MIN_COUNT)));
            fields.remove(IndexingConstants.FACET_MIN_COUNT);
        } else {
            query.setFacetMinCount(IndexingConstants.FACET_MIN_COUNT_DEFAULT);
        }
        //set the sort value for facet: possible values : index or count
        if (fields.get(IndexingConstants.FACET_SORT) != null) {
            query.setFacetSort(fields.get(IndexingConstants.FACET_SORT));
            fields.remove(IndexingConstants.FACET_SORT);
        }
        // set the prefix value for facet
        if (fields.get(IndexingConstants.FACET_PREFIX) != null) {
            query.setFacetPrefix(fields.get(IndexingConstants.FACET_PREFIX));
            fields.remove(IndexingConstants.FACET_PREFIX);
        }
    }
    return queryField;
}

From source file:org.zaizi.sensefy.api.service.SolrSmartAutoCompleteService.java

License:Open Source License

/**
 * <p>/*from  ww w  . j a va  2s .c  o m*/
 * Suggestions from Facet Prefix
 * </p>
 *
 * @param attributesQuery
 * @param termToComplete
 * @param numberOfSuggestions
 * @param suggestionField
 * @param solrCore
 * @return
 * @throws SolrServerException
 */
private List<String> suggestionsFromFacetPrefix(SolrQuery attributesQuery, String termToComplete,
        int numberOfSuggestions, String suggestionField, SolrServer solrCore)
        throws SolrServerException, IOException {
    List<String> suggestions = new ArrayList<String>();

    attributesQuery.setRows(0);
    attributesQuery.setFacet(true);
    attributesQuery.addFacetField(suggestionField);
    attributesQuery.setFacetMinCount(1);
    attributesQuery.setFacetLimit(numberOfSuggestions);
    // if ( termToComplete != null && !termToComplete.isEmpty() )
    attributesQuery.setFacetPrefix(suggestionField, termToComplete);

    QueryResponse attributesQueryResponse;
    attributesQueryResponse = solrCore.query(attributesQuery);
    FacetField facetField = attributesQueryResponse.getFacetField(suggestionField);
    List<FacetField.Count> facets = facetField.getValues();
    for (FacetField.Count singleFacet : facets) {
        suggestions.add(singleFacet.getName());
    }
    return suggestions;
}

From source file:org.zenoss.zep.index.impl.solr.SolrEventIndexBackend.java

License:Open Source License

@Override
protected void searchEventTagSeverities(EventFilter filter, final EventTagSeverityCounter counter)
        throws ZepException {
    assertReady();//from w  w w . jav a2  s  .co  m
    if (filter.getTagFilterCount() == 0) {
        SolrQuery solrQuery = buildSolrQuery(filter, null, null, null, null, SolrFieldFilter.DEFAULTS);
        solrQuery.setRows(0);
        solrQuery.setFields();
        solrQuery.setFacet(true);
        solrQuery.setFacetMinCount(1);
        solrQuery.setFacetLimit(-1);
        solrQuery.addFacetPivotField(IndexConstants.FIELD_ELEMENT_IDENTIFIER, IndexConstants.FIELD_SEVERITY,
                IndexConstants.FIELD_STATUS, IndexConstants.FIELD_COUNT);
        try {
            QueryResponse response = queryServer.query(solrQuery);
            for (PivotField pivotElementId : response.getFacetPivot().getVal(0)) {
                final String uuid = (String) pivotElementId.getValue();
                for (PivotField pivotSeverity : pivotElementId.getPivot()) {
                    final EventSeverity severity = EventSeverity
                            .valueOf(Integer.parseInt((String) pivotSeverity.getValue()));
                    for (PivotField pivotStatus : pivotSeverity.getPivot()) {
                        final EventStatus status = EventStatus
                                .valueOf(Integer.parseInt((String) pivotStatus.getValue()));
                        final boolean acknowledged = EventStatus.STATUS_ACKNOWLEDGED.equals(status);
                        for (PivotField pivotCount : pivotStatus.getPivot()) {
                            final Integer count = pivotCount.getCount() * (Integer) pivotCount.getValue();
                            counter.update(uuid, severity, count, acknowledged);
                        }
                    }
                }
            }
        } catch (SolrServerException e) {
            throw new ZepException(e);
        }
    } else {
        SolrQuery solrQuery = buildSolrQuery(filter, null, null, null, null,
                SolrFieldFilter.SEARCH_EVENT_TAG_SEVERITIES);
        try {
            queryServer.queryAndStreamResponse(solrQuery, new StreamingResponseCallback() {
                @Override
                public void streamSolrDocument(SolrDocument doc) {
                    final EventSeverity severity = EventSeverity
                            .valueOf(Integer.parseInt((String) doc.getFieldValue(FIELD_SEVERITY)));
                    final EventStatus status = EventStatus
                            .valueOf(Integer.parseInt((String) doc.getFieldValue(FIELD_STATUS)));
                    final boolean acknowledged = EventStatus.STATUS_ACKNOWLEDGED.equals(status);
                    final int count = Integer.parseInt((String) doc.getFieldValue(FIELD_COUNT));
                    for (String fieldName : new String[] { FIELD_ELEMENT_IDENTIFIER,
                            FIELD_ELEMENT_SUB_IDENTIFIER }) {
                        final String uuid = (String) doc.getFieldValue(fieldName);
                        counter.update(uuid, severity, count, acknowledged);
                    }
                    for (Object tag : doc.getFieldValues(FIELD_TAGS)) {
                        counter.update((String) tag, severity, count, acknowledged);
                    }
                }

                @Override
                public void streamDocListInfo(long numFound, long start, Float maxScore) {
                    // ignored
                }
            });
        } catch (SolrServerException e) {
            throw new ZepException(e);
        } catch (IOException e) {
            throw new ZepException(e);
        }
    }
}