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

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

Introduction

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

Prototype

public ModifiableSolrParams set(String name, String... val) 

Source Link

Document

Replace any existing parameter with the given name.

Usage

From source file:edu.unc.lib.dl.search.solr.service.SolrSearchService.java

License:Apache License

/**
 * Constructs a SolrQuery object from the search state specified within a SearchRequest object. The request may
 * optionally request to retrieve facet results in addition to search results.
 * //from  w w  w .  j  av  a 2s .co  m
 * @param searchRequest
 * @param isRetrieveFacetsRequest
 * @return
 */
protected SolrQuery generateSearch(SearchRequest searchRequest) {
    SearchState searchState = (SearchState) searchRequest.getSearchState();
    SolrQuery solrQuery = new SolrQuery();
    StringBuilder termQuery = new StringBuilder();

    // Generate search term query string
    addSearchFields(searchState, termQuery);

    // Add range Fields to the query
    addRangeFields(searchState, termQuery);

    // No query terms given, make it an everything query
    StringBuilder query = new StringBuilder();
    if (termQuery.length() == 0) {
        query.append("*:* ");
    } else {
        query.append('(').append(termQuery).append(')');
    }

    // Add access restrictions to query
    try {
        addAccessRestrictions(query, searchRequest.getAccessGroups());
    } catch (AccessRestrictionException e) {
        // If the user doesn't have any access groups, they don't have access to anything, return null.
        LOG.debug("User had no access groups", e);
        return null;
    }

    // Add query
    solrQuery.setQuery(query.toString());

    if (searchState.getResultFields() != null) {
        for (String field : searchState.getResultFields()) {
            String solrFieldName = solrSettings.getFieldName(field);
            if (solrFieldName != null)
                solrQuery.addField(solrFieldName);
        }
    }

    if (searchState.getRollup() != null && searchState.getRollup()) {
        solrQuery.set(GroupParams.GROUP, true);
        if (searchState.getRollupField() == null)
            solrQuery.set(GroupParams.GROUP_FIELD, solrSettings.getFieldName(SearchFieldKeys.ROLLUP_ID.name()));
        else
            solrQuery.set(GroupParams.GROUP_FIELD, solrSettings.getFieldName(searchState.getRollupField()));

        solrQuery.set(GroupParams.GROUP_TOTAL_COUNT, true);
        if (searchState.getFacetsToRetrieve() != null && searchState.getFacetsToRetrieve().size() > 0) {
            solrQuery.set(GroupParams.GROUP_FACET, true);
        }
    }

    // Add sort parameters
    List<SearchSettings.SortField> sortFields = searchSettings.sortTypes.get(searchState.getSortType());
    if (sortFields != null) {
        for (int i = 0; i < sortFields.size(); i++) {
            SearchSettings.SortField sortField = sortFields.get(i);
            SolrQuery.ORDER sortOrder = SolrQuery.ORDER.valueOf(sortField.getSortOrder());
            if (!searchState.getSortNormalOrder())
                sortOrder = sortOrder.reverse();
            solrQuery.addSort(solrSettings.getFieldName(sortField.getFieldName()), sortOrder);
        }
    }

    // Set requested resource types
    String resourceTypeFilter = this.getResourceTypeFilter(searchState.getResourceTypes());
    if (resourceTypeFilter != null) {
        solrQuery.addFilterQuery(resourceTypeFilter);
    }

    // Turn on faceting
    if (searchRequest.isRetrieveFacets()) {
        solrQuery.setFacet(true);
        solrQuery.setFacetMinCount(1);
        if (searchState.getBaseFacetLimit() != null)
            solrQuery.setFacetLimit(searchState.getBaseFacetLimit());

        if (searchState.getFacetsToRetrieve() != null) {
            // Add facet fields
            for (String facetName : searchState.getFacetsToRetrieve()) {
                String facetField = solrSettings.getFieldName(facetName);
                if (facetField != null)
                    solrQuery.addFacetField(solrSettings.getFieldName(facetName));
            }
        }
    }

    // Override the base facet limit if overrides are given.
    if (searchState.getFacetLimits() != null) {
        for (Entry<String, Integer> facetLimit : searchState.getFacetLimits().entrySet()) {
            solrQuery.add("f." + solrSettings.getFieldName(facetLimit.getKey()) + ".facet.limit",
                    facetLimit.getValue().toString());
        }
    }

    // Add facet limits
    Map<String, Object> facets = searchState.getFacets();
    if (facets != null) {
        Iterator<Entry<String, Object>> facetIt = facets.entrySet().iterator();
        while (facetIt.hasNext()) {
            Entry<String, Object> facetEntry = facetIt.next();

            if (facetEntry.getValue() instanceof String) {
                LOG.debug("Adding facet " + facetEntry.getKey() + " as a String");
                // Add Normal facets
                solrQuery.addFilterQuery(solrSettings.getFieldName(facetEntry.getKey()) + ":\""
                        + SolrSettings.sanitize((String) facetEntry.getValue()) + "\"");
            } else {
                LOG.debug("Adding facet " + facetEntry.getKey() + " as a "
                        + facetEntry.getValue().getClass().getName());
                facetFieldUtil.addToSolrQuery(facetEntry.getValue(), solrQuery);
            }
        }
    }

    // Scope hierarchical facet results to the highest tier selected within the facet tree
    if (searchRequest.isRetrieveFacets() && searchRequest.isApplyCutoffs()
            && searchState.getFacetsToRetrieve() != null) {
        Set<String> facetsQueried = searchState.getFacets().keySet();
        // Apply closing cutoff to all cutoff facets that are being retrieved but not being queried for
        for (String fieldKey : searchState.getFacetsToRetrieve()) {
            if (!facetsQueried.contains(fieldKey)) {
                facetFieldUtil.addDefaultFacetPivot(fieldKey, solrQuery);
            }
        }

        // Add individual facet field sorts if they are present.
        if (searchState.getFacetSorts() != null) {
            for (Entry<String, String> facetSort : searchState.getFacetSorts().entrySet()) {
                solrQuery.add("f." + solrSettings.getFieldName(facetSort.getKey()) + ".facet.sort",
                        facetSort.getValue());
            }
        }
    }

    // Set Navigation options
    if (searchState.getStartRow() != null)
        solrQuery.setStart(searchState.getStartRow());
    if (searchState.getRowsPerPage() != null)
        solrQuery.setRows(searchState.getRowsPerPage());

    return solrQuery;
}

From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java

License:Apache License

private JSONObject getPopularGenomes() {
    JSONObject jsonData = null;//from w w w.  ja  va 2 s  .  co  m
    JSONArray list = new JSONArray();

    DataApiHandler dataApi = new DataApiHandler();

    for (String genomeId : REFERENCE_GENOME_IDS) {

        Genome genome = dataApi.getGenome(genomeId);

        // construct genome
        JSONObject popGenome = new JSONObject();
        popGenome.put("link", URL_GENOMEOVERVIEW_TAB.replace("{cType}", "genome").replace("{cId}", genomeId));
        popGenome.put("popularName", genome.getGenomeName());
        popGenome.put("gb_link", URL_GENOMEBROWSER.replace("{cType}", "genome").replace("{cId}", genomeId));

        // meta data
        JSONObject meta = new JSONObject();
        meta.put("genome_status", genome.getGenomeStatus());
        meta.put("completion_date", genome.hasCompletionDate() ? genome.getCompletionDate() : "");
        meta.put("collection_date", genome.hasCollectionDate() ? genome.getCollectionDate() : "");
        meta.put("isolation_country", genome.hasIsolationCountry() ? genome.getIsolationCountry() : "");
        meta.put("host_name", genome.hasHostName() ? genome.getHostName() : "");
        meta.put("disease", genome.hasDisease() ? StringUtils.join(genome.getDisease(), ", ") : "");
        meta.put("chromosomes", genome.getChromosomes());
        meta.put("plasmids", genome.getPlasmids());
        meta.put("contigs", genome.getContigs());
        meta.put("genome_length", genome.getGenomeLength());

        popGenome.put("metadata", meta);

        JSONArray data = new JSONArray();

        // Features
        JSONObject ft = new JSONObject();
        ft.put("description", "Features");
        ft.put("link", URL_FEATURETABLE_TAB.replace("{cType}", "genome").replace("{cId}", genomeId)
                .replace("{featureType}", "").replace("{filterType}", ""));
        ft.put("picture", "/patric/images/icon-popular-feature.png");
        ft.put("data", genome.getPatricCds());
        data.add(ft);

        // Pathways
        JSONObject pw = new JSONObject();
        pw.put("description", "Pathways");
        pw.put("link",
                URL_PATHWAY_TAB.replace("{cType}", "genome").replace("{cId}", genomeId).replace("{pId}", ""));
        pw.put("picture", "/patric/images/icon-popular-pathway.png");

        int cntPathway = 0;
        try {
            SolrQuery query = new SolrQuery("genome_id:" + genomeId);
            // {stat:{field:{field:genome_id,facet:{pathway_count:"unique(pathway_id)"}}}}}
            query.setRows(0).setFacet(true).set("json.facet",
                    "{stat:{field:{field:genome_id,facet:{pathway_count:\"unique(pathway_id)\"}}}}}");

            LOGGER.trace("[{}] {}", SolrCore.PATHWAY.getSolrCoreName(), query);

            String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query);

            Map resp = jsonReader.readValue(apiResponse);
            Map facets = (Map) resp.get("facets");
            List<Map> buckets = (List) ((Map) facets.get("stat")).get("buckets");
            Map firstPathway = buckets.get(0);
            cntPathway = (Integer) firstPathway.get("pathway_count");
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        pw.put("data", cntPathway);
        data.add(pw);

        // Protein Family
        JSONObject pf = new JSONObject();
        pf.put("description", "Protein Families");
        pf.put("link", URL_PROTEINFAMILY_TAB.replace("{cType}", "genome").replace("{cId}", genomeId));
        pf.put("picture", "/patric/images/icon-popular-proteinfamily.png");

        // Experiment
        JSONObject tr = new JSONObject();
        tr.put("description", "Transcriptomic Experiments");
        tr.put("link", URL_TRANSCRIPTOMICS_TAB.replace("{cType}", "genome").replace("{cId}", genomeId)
                .replace("{kw}", ""));

        long numFound = 0;
        try {
            SolrQuery query = new SolrQuery("genome_ids:" + genomeId);
            query.setRows(0);

            LOGGER.trace("[{}] {}", SolrCore.TRANSCRIPTOMICS_EXPERIMENT.getSolrCoreName(), query);

            String apiResponse = dataApi.solrQuery(SolrCore.TRANSCRIPTOMICS_EXPERIMENT, query);

            Map resp = jsonReader.readValue(apiResponse);
            Map respBody = (Map) resp.get("response");
            numFound = (Integer) respBody.get("numFound");
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        tr.put("picture", "/patric/images/icon-popular-experiment.png");
        tr.put("data", (int) numFound);

        data.add(tr);

        try {
            SolrQuery query = new SolrQuery(
                    "figfam_id:[* TO *] AND annotation:PATRIC AND genome_id:" + genomeId);
            query.setRows(0);

            LOGGER.trace("[{}] {}", SolrCore.FEATURE.getSolrCoreName(), query);

            String apiResponse = dataApi.solrQuery(SolrCore.FEATURE, query);

            Map resp = jsonReader.readValue(apiResponse);
            Map respBody = (Map) resp.get("response");

            pf.put("data", respBody.get("numFound"));
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
        data.add(pf);

        popGenome.put("popularData", data);

        list.add(popGenome);
    }
    if (list.size() > 0) {
        jsonData = new JSONObject();
        jsonData.put("popularList", list);
        jsonData.put("popularTitle", "Select Genomes");
    }
    return jsonData;
}

From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java

License:Apache License

private JSONObject getPopularGenomesForPathways() {

    JSONObject jsonData = null;/*from  w ww  . j a v a 2s.c om*/
    JSONArray list = new JSONArray();

    for (String genomeId : REFERENCE_GENOME_IDS) {
        Genome genome = dataApi.getGenome(genomeId);

        // construct genome
        JSONObject popGenome = new JSONObject();

        popGenome.put("popularName", genome.getGenomeName());
        popGenome.put("link",
                URL_PATHWAY_TAB.replace("{cType}", "genome").replace("{cId}", genomeId).replace("{pId}", ""));

        JSONArray data = new JSONArray();

        LinkedList<Map<String, String>> pathwayList = new LinkedList<>();

        try {
            //{stat:{field:{field:pathway_id,sort:{ec_count:desc},facet:{ec_count:"unique(ec_number)",gene_count:"unique(feature_id)",field:{field:pathway_name}}}}}
            SolrQuery query = new SolrQuery("genome_id:" + genomeId).addFilterQuery("annotation:PATRIC");
            query.setRows(0).setFacet(true).set("json.facet",
                    "{stat:{field:{field:pathway_id,sort:{ec_count:desc},facet:{ec_count:\"unique(ec_number)\",gene_count:\"unique(feature_id)\",field:{field:pathway_name}}}}}");

            LOGGER.debug("getPopularGenomesForPathways: [{}] {}", SolrCore.PATHWAY.getSolrCoreName(), query);

            String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query);

            Map resp = jsonReader.readValue(apiResponse);
            Map facets = (Map) resp.get("facets");
            List<Map> buckets = (List) ((Map) facets.get("stat")).get("buckets");

            for (Map bucket : buckets) {
                Map<String, String> pathway = new HashMap<>();
                pathway.put("id", bucket.get("val").toString());
                pathway.put("ec_count", bucket.get("ec_count").toString());
                pathway.put("gene_count", bucket.get("gene_count").toString());

                // getting name
                List<Map> subBuckets = (List) ((Map) bucket.get("field")).get("buckets");
                pathway.put("name", subBuckets.get(0).get("val").toString());

                pathwayList.add(pathway);
            }
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }

        for (Map<String, String> pathway : pathwayList) {
            JSONObject pw = new JSONObject();

            pw.put("name", pathway.get("name"));
            pw.put("name_link", URL_PATHWAY_TAB.replace("{cType}", "genome").replace("{cId}", genomeId)
                    .replace("{pId}", pathway.get("id")));
            // pw.put("class", item.get("pathway_class"));
            pw.put("gene_count", pathway.get("gene_count"));
            pw.put("gene_link",
                    URL_PATHWAY_GENE_TAB.replace("{cId}", genomeId).replace("{pId}", pathway.get("id")));
            pw.put("ec_count", pathway.get("ec_count"));
            pw.put("ec_link",
                    URL_PATHWAY_EC_TAB.replace("{cId}", genomeId).replace("{pId}", pathway.get("id")));

            data.add(pw);
        }
        popGenome.put("popularData", data);
        list.add(popGenome);
    }
    if (list.size() > 0) {
        jsonData = new JSONObject();
        jsonData.put("popularList", list);
        jsonData.put("popularTitle", "Select Genomes");
    }
    return jsonData;
}

From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java

License:Apache License

private JSONObject getPathwayECDist() {
    JSONObject jsonData;/*from  w  w w. ja  v a2s .c  om*/
    JSONArray series = new JSONArray();

    for (Integer txId : GENUS_TAXON_IDS) {
        int total = 0;
        List<Integer> distribution = new LinkedList<>();

        // {stat:{field:{field:pathway_id,limit:-1,facet:{ec_count:"unique(ec_number)",genome_count:"unique(genome_id)",genome_ec_count:"unique(genome_ec)"}}}}
        try {
            SolrQuery query = new SolrQuery("annotation:PATRIC");
            query.addFilterQuery(SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id",
                    "genome_status:(Complete OR WGS) AND taxon_lineage_ids:" + txId));
            query.setRows(0).setFacet(true).set("json.facet",
                    "{stat:{field:{field:pathway_id,limit:-1,facet:{ec_count:\"unique(ec_number)\",genome_count:\"unique(genome_id)\",genome_ec_count:\"unique(genome_ec)\"}}}}");

            LOGGER.debug("getPathwayECDist: [{}] {}", SolrCore.PATHWAY.getSolrCoreName(), query);

            String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query);

            Map resp = jsonReader.readValue(apiResponse);
            Map facets = (Map) resp.get("facets");
            List<Map> buckets = (List) ((Map) facets.get("stat")).get("buckets");

            int bin1 = 0, bin2 = 0, bin3 = 0, bin4 = 0, bin5 = 0;

            for (Map bucket : buckets) {

                double ec_count = ((Integer) bucket.get("ec_count")).doubleValue();
                double genome_count = ((Integer) bucket.get("genome_count")).doubleValue();
                double genome_ec_count = ((Integer) bucket.get("genome_ec_count")).doubleValue();

                long bin = Math.round(genome_ec_count / genome_count / ec_count * 100);

                //               LOGGER.trace("calculating conservation, ec:{}, genome:{}, genome_ec:{}, bin:{}", ec_count, genome_count, genome_ec_count, bin);
                if (bin < 20) {
                    bin5++;
                } else if (bin >= 20 && bin < 40) {
                    bin4++;
                } else if (bin >= 40 && bin < 60) {
                    bin3++;
                } else if (bin >= 60 && bin < 80) {
                    bin2++;
                } else if (bin >= 80) {
                    bin1++;
                }
                total++;
            }
            distribution.addAll(Arrays.asList(bin1, bin2, bin3, bin4, bin5));
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }

        Taxonomy taxonomy = dataApi.getTaxonomy(txId);

        JSONObject item = new JSONObject();
        item.put("pathogen", taxonomy.getTaxonName());
        item.put("total", total);
        item.put("dist", distribution);

        series.add(item);
    }

    jsonData = new JSONObject();
    jsonData.put("chart_title", "Pathway Conservation in Pathogenic Bacteria");
    jsonData.put("chart_desc",
            "The graph below shows conservation of metabolic pathways across percentage of total genomes in each pathogenic genus.");
    jsonData.put("data", series);

    return jsonData;
}

From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java

License:Apache License

private Map<String, Integer> getFIGFamStat(int taxonId) {
    Map<String, Integer> stat = new HashMap<>();

    try {//w ww.ja  v a2  s.  c o m
        final String filterCondition = SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id",
                "taxon_lineage_ids:" + taxonId);

        Map response = dataApi.getFieldFacets(SolrCore.FEATURE, "feature_type:CDS AND annotation:PATRIC",
                filterCondition, "figfam_id");
        Map figfamFacets = (Map) ((Map) response.get("facets")).get("figfam_id");
        int total = figfamFacets.size();

        response = dataApi.getFieldFacets(SolrCore.FEATURE, "product:(hypothetical AND protein)",
                filterCondition, "figfam_id");
        Map hypotheticalFacets = (Map) ((Map) response.get("facets")).get("figfam_id");
        int hypothetical = hypotheticalFacets.size();

        stat.put("total", total);
        stat.put("hypothetical", hypothetical);
        stat.put("functional", (total - hypothetical));

        // counting core vs accessary
        int countCore = 0;
        SolrQuery query = new SolrQuery("*:*").addFilterQuery(filterCondition).setRows(0).setFacet(true);
        query.set("json.facet",
                "{stat:{field:{field:figfam_id,limit:-1,allBuckets:true,facet:{genome_count:\"unique(genome_id)\"}}}}");

        LOGGER.debug("getFIGFamStat(): [{}] {}", SolrCore.FEATURE.getSolrCoreName(), query);

        String apiResponse = dataApi.solrQuery(SolrCore.FEATURE, query);

        Map resp = jsonReader.readValue(apiResponse);
        Map facets = (Map) resp.get("facets");
        Map allBuckets = (Map) ((Map) facets.get("stat")).get("allBuckets");

        double genomeCount = ((Integer) allBuckets.get("genome_count")).doubleValue();
        double cutoff = 0.95 * genomeCount;

        List<Map> buckets = (List) ((Map) facets.get("stat")).get("buckets");

        for (Map bucket : buckets) {
            if (((Integer) bucket.get("genome_count")).doubleValue() > cutoff) {
                countCore++;
            }
        }
        stat.put("core", countCore);
        stat.put("accessory", (total - countCore));
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    return stat;
}

From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java

License:Apache License

private JSONArray getFIGFamConservationDistribution(int taxonId) {
    JSONArray dist = new JSONArray();

    try {/*  w  w  w.  j  a  v a 2 s.  c o  m*/
        Map<Integer, List<String>> distMap = new LinkedHashMap<>();

        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("feature_type:CDS AND annotation:PATRIC");
        query.addFilterQuery(
                SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id", "taxon_lineage_ids:" + taxonId));
        query.setRows(0).setFacet(true).set("json.facet",
                "{stat:{field:{field:figfam_id,limit:-1,allBuckets:true,facet:{genome_count:\"unique(genome_id)\"}}}}");

        LOGGER.trace("getFIGFamConservationDistribution(), [{}] {}", SolrCore.FEATURE.getSolrCoreName(), query);

        String apiResponse = dataApi.solrQuery(SolrCore.FEATURE, query);

        Map resp = jsonReader.readValue(apiResponse);
        Map facets = (Map) resp.get("facets");

        Map allBuckets = (Map) ((Map) facets.get("stat")).get("allBuckets");
        double totalGenomeCount = ((Integer) allBuckets.get("genome_count")).doubleValue();

        List<Map> buckets = (List<Map>) ((Map) facets.get("stat")).get("buckets");

        for (Map bucket : buckets) {
            String figfamID = (String) bucket.get("val");
            double genomeCount = ((Integer) bucket.get("genome_count")).doubleValue();
            int groupHash = ((Double) Math.ceil(genomeCount / totalGenomeCount * 10.0d)).intValue();

            //            LOGGER.trace("group hashing.. {}:{}/{} -> {}", figfamID, genomeCount, totalGenomeCount, groupHash);
            if (distMap.get(groupHash) == null) {
                distMap.put(groupHash, new LinkedList<String>());
            }
            distMap.get(groupHash).add(figfamID);
        }

        for (int i = 1; i <= 10; i++) {
            JSONObject item = new JSONObject();
            if (distMap.get(i) != null && !distMap.get(i).isEmpty()) {
                item.put("x", (i) + "0%");
                item.put("y", distMap.get(i).size());
            } else {
                item.put("x", (i) + "0%");
                item.put("y", 0);
            }
            dist.add(item);
        }
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    return dist;
}

From source file:edu.vt.vbi.patric.common.DataApiHandler.java

License:Apache License

/**
 * wrapper function of field facet query
 *
 * @param core SolrCore/*  w  w  w. j  a  va 2  s .c o  m*/
 * @param queryParam query condition
 * @param filterParam filter condition
 * @param facetFields comma separated list of fields
 */
public Map getFieldFacets(SolrCore core, String queryParam, String filterParam, String facetFields)
        throws IOException {
    Map<String, Object> res = new HashMap<>();
    SolrQuery query = new SolrQuery();

    query.setQuery(queryParam);
    if (filterParam != null) {
        query.addFilterQuery(filterParam);
    }
    query.setRows(0).setFacet(true).setFacetLimit(-1).setFacetMinCount(1)
            .setFacetSort(FacetParams.FACET_SORT_COUNT).set("json.nl", "map");
    query.addFacetField(facetFields.split(","));

    List<String> fields = Arrays.asList(facetFields.split(","));

    LOGGER.trace("getFieldFacets: [{}] {}", core.getSolrCoreName(), query.toString());
    String response = this.solrQuery(core, query);
    Map resp = jsonParser.readValue(response);
    Map facet_fields = (Map) ((Map) resp.get("facet_counts")).get("facet_fields");

    Map<String, Object> facets = new HashMap<>();
    for (String field : fields) {
        Map values = (Map) facet_fields.get(field);
        Map<String, Integer> facetValues = new LinkedHashMap<>();

        for (Map.Entry<String, Integer> entry : (Iterable<Map.Entry>) values.entrySet()) {
            facetValues.put(entry.getKey(), entry.getValue());
        }

        facets.put(field, facetValues);
    }

    res.put("total", ((Map) resp.get("response")).get("numFound"));
    res.put("facets", facets);

    return res;
}

From source file:edu.vt.vbi.patric.common.DataApiHandler.java

License:Apache License

public SolrQuery buildSolrQuery(Map<String, String> key, String sorts, String facets, int start, int end,
        boolean highlight) {

    SolrQuery query = new SolrQuery();
    SolrInterface solr = new SolrInterface();

    // Processing key map
    query.setQuery(StringHelper.stripQuoteAndParseSolrKeywordOperator(key.get("keyword")));

    if (key.containsKey("filter") && key.get("filter") != null) {
        query.addFilterQuery(key.get("filter"));
    }// w ww.j  av a2s  .c  om
    if (key.containsKey("filter2") && key.get("filter2") != null) {
        query.addFilterQuery(key.get("filter2"));
    }

    // use SolrJoin if possible
    if (key.containsKey("join")) {
        query.addFilterQuery(key.get("join"));
    }

    if (key.containsKey("fields") && !key.get("fields").equals("")) {
        query.addField(key.get("fields"));
    }

    // sort conditions
    if (sorts != null && !sorts.equals("") && !sorts.equals("[]")) {
        try {
            JSONArray sorter = (JSONArray) new JSONParser().parse(sorts);
            for (Object aSort : sorter) {
                JSONObject jsonSort = (JSONObject) aSort;
                query.addSort(SolrQuery.SortClause.create(jsonSort.get("property").toString(),
                        jsonSort.get("direction").toString().toLowerCase()));
            }
        } catch (ParseException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    // facet conditions
    if (facets != null && !facets.equals("") && !facets.equals("{}")) {
        query.setFacet(true).setFacetMinCount(1).setFacetLimit(-1).setFacetSort(FacetParams.FACET_SORT_COUNT)
                .set("json.nl", "map");

        try {
            JSONObject facetConditions = (JSONObject) new JSONParser().parse(facets);

            if (facetConditions.containsKey("facet.sort")) {
                String facetSort = facetConditions.get("facet.sort").toString();
                if (facetSort.equals("index")) {
                    query.setFacetSort(FacetParams.FACET_SORT_INDEX);
                }
            }

            if (facetConditions.containsKey("field_facets")) {
                String[] fieldFacets = facetConditions.get("field_facets").toString().split(",");
                query.addFacetField(fieldFacets);
            }

            if (facetConditions.containsKey("date_range_facets")
                    && !facetConditions.get("date_range_facets").equals("")) {
                String[] dateRangeFacets = facetConditions.get("date_range_facets").toString().split(",");
                for (String field : dateRangeFacets) {
                    query.addDateRangeFacet(field, solr.getRangeStartDate(), solr.getRangeEndDate(),
                            solr.getRangeDate());
                }
            }
        } catch (ParseException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    // start & end
    query.setStart(start); // setting starting index

    if (end == -1) {
        query.setRows(MAX_ROWS);
    } else {
        query.setRows(end);
    }

    // highlight
    if (highlight) {
        query.set("hl", "on").set("hl.fl", "*");
    }

    return query;
}

From source file:edu.vt.vbi.patric.common.FacetHelper.java

License:Apache License

private static JSONObject getSingleFacetsData(DataApiHandler dataApi, SolrCore core, String keyword,
        String single_facet, String[] facets, String fq) throws IOException, ParseException {

    SolrInterface solr = new SolrInterface();

    keyword = StringHelper.stripQuoteAndParseSolrKeywordOperator(keyword);

    int beginindex = keyword.indexOf(" AND (" + single_facet);
    int endindex = 0;

    StringBuffer s = new StringBuffer(keyword);

    if (beginindex < 0) {
        beginindex = keyword.indexOf("(" + single_facet);
        endindex = keyword.indexOf(") AND ", beginindex);
        if (endindex < 0) {
            endindex = keyword.indexOf("))", beginindex);

            // TODO: this cause java.lang.StringIndexOutOfBoundsException: String index out of range: -1
            // when Patric Libs keyword - (*) and endindex: 2
            LOGGER.debug("string:{}, beginIndex: {}, endIndex:{}", s, beginindex, endindex);
            if (endindex > 0) {
                s.delete(beginindex, endindex + 2);
            }//w w w. ja v  a 2  s .  co  m
        } else {
            s.delete(beginindex, endindex + 6);
        }
    } else {
        endindex = keyword.indexOf("))", beginindex);
        if (endindex == -1) {
            endindex = keyword.indexOf("])", beginindex);
        }
        s.delete(beginindex, endindex + 2);
    }
    if (s.length() == 0)
        s.append("(*)");

    SolrQuery query = new SolrQuery();
    query.setQuery(s.toString());
    if (fq != null) {
        query.setFilterQueries(fq);
    }

    query.setStart(0).setRows(1).setFacet(true).setFacetMinCount(1).set("json.nl", "map");

    for (String facet : facets) {
        if (!facet.equals("completion_date") && !facet.equals("release_date")) {
            query.addFacetField(facet);
        } else {
            query.addDateRangeFacet(facet, solr.getRangeStartDate(), solr.getRangeEndDate(),
                    solr.getRangeDate());
        }
    }

    String apiResponse = dataApi.solrQuery(core, query);

    Map resp = jsonMapReader.readValue(apiResponse);
    Map respBody = (Map) resp.get("response");

    JSONObject ret = new JSONObject();
    ret.put("response", new JSONObject(respBody));
    ret.put("facets", FacetHelper.formatFacetTree((Map) resp.get("facet_counts")));

    return ret;
}

From source file:edu.vt.vbi.patric.portlets.GlobalSearch.java

License:Apache License

private Map processGlobalSearchFeature(ResourceRequest request) throws IOException {

    DataApiHandler dataApi = new DataApiHandler(request);
    String keyword = request.getParameter("keyword");
    String need = request.getParameter("need");

    SolrQuery query = new SolrQuery(StringHelper.stripQuoteAndParseSolrKeywordOperator(keyword));
    if (need.equals("search")) {
        query.setRows(3).set("hl", "on").set("hl.fl", "*");
    } else {/*  w ww .  ja  va2 s .co m*/
        query.setRows(dataApi.MAX_ROWS);
    }

    query.setFields(StringUtils.join(DownloadHelper.getFieldsForFeatures(), ","));
    query.addFilterQuery("!feature_type:source");
    query.addFilterQuery("!annotation:BRC1");

    LOGGER.trace("processGlobalSearch: [{}] {}", SolrCore.FEATURE.getSolrCoreName(), query);
    String apiResponse = dataApi.solrQuery(SolrCore.FEATURE, query);

    Map resp = jsonReader.readValue(apiResponse);

    return resp;
}