Example usage for org.apache.solr.client.solrj.util ClientUtils escapeQueryChars

List of usage examples for org.apache.solr.client.solrj.util ClientUtils escapeQueryChars

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj.util ClientUtils escapeQueryChars.

Prototype


public static String escapeQueryChars(String s) 

Source Link

Document

See: <a href="https://www.google.com/?gws_rd=ssl#q=lucene+query+parser+syntax">Lucene query parser syntax</a> for more information on Escaping Special Characters

Usage

From source file:org.phenotips.variantstore.db.solr.SolrController.java

License:Open Source License

@Override
public Map<String, List<GAVariant>> getIndividualsWithGene(String gene, List<String> variantEffects,
        Map<String, Double> alleleFrequencies, int n, int totIndividuals) {
    Map<String, List<GAVariant>> map = new HashMap<>();

    checkArgument(n != 0, "n cannot be zero");

    checkNotNull(gene, "gene cannot be null");
    checkArgument(!"".equals(gene), "gene cannot be empty");

    checkNotNull(variantEffects, "effects cannot be null");
    checkArgument(variantEffects.size() != 0, "effects cannot be empty");

    checkNotNull(alleleFrequencies, "allele frequencies cannot be null");
    checkArgument(alleleFrequencies.size() != 0, "allele frequencies cannot be empty");

    /** Build Query String **/

    // alleleFreq = copiesSum / 2*totIndividuals
    int copiesSum = (int) (alleleFrequencies.get(DB_FREQUENCY_FIELD) * totIndividuals * 2);

    StringBuilder builder = new StringBuilder();
    for (String effect : variantEffects) {
        builder.append(VariantsSchema.GENE_EFFECT).append(":").append(ClientUtils.escapeQueryChars(effect))
                .append(" OR ");
    }// w  w  w.  jav  a 2s  .c o m
    // Strip final ' OR '
    String effectQuery = builder.toString();
    effectQuery = effectQuery.substring(0, effectQuery.length() - 4);

    // Find ExAC AF under the specified frequency, or where ExAC is null.
    String exacQuery = String.format("(-%s:[* TO *] AND *:*) OR %s:[0 TO %s]", VariantsSchema.EXAC_AF,
            VariantsSchema.EXAC_AF,
            ClientUtils.escapeQueryChars(String.valueOf(alleleFrequencies.get(EXAC_FREQUENCY_FIELD))));

    String queryString = String.format("%s:[* TO %s] AND %s:%s AND (%s) AND (%s)", VariantsSchema.AC_TOT,
            copiesSum, VariantsSchema.GENE, ClientUtils.escapeQueryChars(gene), effectQuery, exacQuery);

    SolrQuery q = new SolrQuery().setQuery(queryString).setFilterQueries(queryString);

    q.setRows(300);

    QueryResponse resp;

    try {
        resp = server.query(q);
        map = SolrVariantUtils
                .variantListToCallsetMap(SolrVariantUtils.documentListToMapList(resp.getResults()));
    } catch (SolrServerException | IOException e) {
        logger.error("Error getting individals with variant", e);
    }

    return map;
}

From source file:org.phenotips.vocabulary.internal.GeneNomenclature.java

License:Open Source License

@Override
public VocabularyTerm getTerm(String symbol) {
    String escapedSymbol = ClientUtils.escapeQueryChars(symbol);

    VocabularyTerm result = getTermById(escapedSymbol);
    if (result != null) {
        return result;
    }/*from   w  ww  . j  a va2  s .  c  om*/
    result = getTermBySymbolOrAlias(escapedSymbol);
    if (result != null) {
        return result;
    }
    result = getTermByAlternativeId(escapedSymbol);
    return result;
}

From source file:org.phenotips.vocabulary.internal.GeneNomenclature.java

License:Open Source License

private SolrParams produceDynamicSolrParams(String originalQuery, Integer rows, String sort,
        String customFilter) {//from  ww  w. ja  v a  2  s .co  m
    String escapedQuery = ClientUtils.escapeQueryChars(originalQuery.trim());

    ModifiableSolrParams params = new ModifiableSolrParams();
    params.add(CommonParams.Q, escapedQuery);
    params.add(CommonParams.ROWS, rows.toString());
    if (StringUtils.isNotBlank(sort)) {
        params.add(CommonParams.SORT, sort);
    }
    params.add(CommonParams.FQ, StringUtils.defaultIfBlank(customFilter, "status:Approved"));
    return params;
}

From source file:org.phenotips.vocabulary.internal.RemoteGeneNomenclature.java

License:Open Source License

private StringBuilder processQueryPart(StringBuilder query, Map.Entry<String, ?> field,
        boolean includeOperator) {
    if (Collection.class.isInstance(field.getValue()) && ((Collection<?>) field.getValue()).isEmpty()) {
        return query;
    }//from www  .j  av a 2s. c om
    if (Map.class.isInstance(field.getValue())) {
        if (QUERY_OPERATORS.containsKey(field.getKey())) {
            @SuppressWarnings("unchecked")
            Map.Entry<String, Map<String, ?>> subquery = (Map.Entry<String, Map<String, ?>>) field;
            return processSubquery(query, subquery);
        } else {
            this.logger.warn("Invalid subquery operator: {}", field.getKey());
            return query;
        }
    }
    query.append(' ');
    if (includeOperator) {
        query.append(QUERY_OPERATORS.get(DEFAULT_OPERATOR));
    }

    query.append(ClientUtils.escapeQueryChars(field.getKey()));
    query.append(":(");
    if (Collection.class.isInstance(field.getValue())) {
        for (Object value : (Collection<?>) field.getValue()) {
            String svalue = String.valueOf(value);
            if (svalue.endsWith(WILDCARD)) {
                svalue = ClientUtils.escapeQueryChars(StringUtils.removeEnd(svalue, WILDCARD)) + WILDCARD;
            } else {
                svalue = ClientUtils.escapeQueryChars(svalue);
            }
            query.append(svalue);
            query.append(' ');
        }
    } else {
        String svalue = String.valueOf(field.getValue());
        if (svalue.endsWith(WILDCARD)) {
            svalue = ClientUtils.escapeQueryChars(StringUtils.removeEnd(svalue, WILDCARD)) + WILDCARD;
        } else {
            svalue = ClientUtils.escapeQueryChars(svalue);
        }
        query.append(svalue);
    }
    query.append(')');
    return query;
}

From source file:org.phenotips.vocabulary.internal.solr.AbstractSolrVocabulary.java

License:Open Source License

@Override
public VocabularyTerm getTerm(String id) {
    VocabularyTerm result = this.externalServicesAccess.getTermCache().get(id);
    if (result == null) {
        ModifiableSolrParams params = new ModifiableSolrParams();
        params.set(CommonParams.Q, ID_FIELD_NAME + ':' + ClientUtils.escapeQueryChars(id));
        SolrDocumentList allResults = this.search(params);
        if (allResults != null && !allResults.isEmpty()) {
            result = new SolrVocabularyTerm(allResults.get(0), this);
            this.externalServicesAccess.getTermCache().set(id, result);
        } else {/*w ww.j av a2  s  .  c om*/
            this.externalServicesAccess.getTermCache().set(id, EMPTY_MARKER);
        }
    }
    return (result == EMPTY_MARKER) ? null : result;
}

From source file:org.phenotips.vocabulary.internal.solr.AbstractSolrVocabulary.java

License:Open Source License

@Override
public Set<VocabularyTerm> getTerms(Collection<String> ids) {
    Set<VocabularyTerm> result = new LinkedHashSet<VocabularyTerm>();
    StringBuilder query = new StringBuilder("id:(");
    for (String id : ids) {
        VocabularyTerm cachedTerm = this.externalServicesAccess.getTermCache().get(id);
        if (cachedTerm != null) {
            if (cachedTerm != EMPTY_MARKER) {
                result.add(cachedTerm);/* www.  j a v  a  2 s.  com*/
            }
        } else {
            query.append(ClientUtils.escapeQueryChars(id));
            query.append(' ');
        }
    }
    query.append(')');

    // There's at least one more term not found in the cache
    if (query.length() > 5) {
        for (SolrDocument doc : this.search(SolrQueryUtils.transformQueryToSolrParams(query.toString()))) {
            result.add(new SolrVocabularyTerm(doc, this));
        }
    }
    return result;
}

From source file:org.phenotips.vocabulary.internal.solr.AbstractSolrVocabulary.java

License:Open Source License

/**
 * Generate a Lucene query from a map of parameters, to be used in the "q" parameter for Solr.
 *
 * @param fieldValues a map with term meta-property values that must be matched by the returned terms; the keys are
 *            property names, like {@code id}, {@code description}, {@code is_a}, and the values can be either a
 *            single value, or a collection of values that can (OR) be matched by the term;
 * @return the String representation of the equivalent Lucene query
 *//*from   ww w . ja v  a  2 s .  c om*/
protected String generateLuceneQuery(Map<String, ?> fieldValues) {
    StringBuilder query = new StringBuilder();
    for (Map.Entry<String, ?> field : fieldValues.entrySet()) {
        if (Collection.class.isInstance(field.getValue()) && ((Collection<?>) field.getValue()).isEmpty()) {
            continue;
        }
        query.append('+');
        query.append(ClientUtils.escapeQueryChars(field.getKey()));
        query.append(":(");
        if (Collection.class.isInstance(field.getValue())) {
            for (Object value : (Collection<?>) field.getValue()) {
                query.append(ClientUtils.escapeQueryChars(String.valueOf(value)));
                query.append(' ');
            }
        } else {
            String value = String.valueOf(field.getValue());
            if ("*".equals(value)) {
                query.append(value);
            } else {
                query.append(ClientUtils.escapeQueryChars(value));
            }
        }
        query.append(')');
    }
    return query.toString();
}

From source file:org.phenotips.vocabulary.internal.solr.GeneNomenclature.java

License:Open Source License

@Override
public VocabularyTerm getTerm(String symbol) {
    if (StringUtils.isBlank(symbol)) {
        return null;
    }//from w  ww .  j a  v a2s. c om
    final String id = StringUtils.contains(symbol, SEPARATOR) ? StringUtils.substringAfter(symbol, SEPARATOR)
            : symbol;
    return requestTerm(ClientUtils.escapeQueryChars(id));
}

From source file:org.phenotips.vocabulary.internal.solr.GeneNomenclature.java

License:Open Source License

private SolrQuery produceDynamicSolrParams(Map<String, String> staticOptions, String originalQuery,
        Integer rows, String sort, String customFilter) {
    String escapedQuery = ClientUtils.escapeQueryChars(originalQuery.trim());

    SolrQuery params = new SolrQuery(escapedQuery);
    for (Map.Entry<String, String> option : staticOptions.entrySet()) {
        params.set(option.getKey(), option.getValue());
    }/*from  ww w . j  a  va 2  s .  c  o  m*/
    params.setRows(rows);
    if (StringUtils.isNotBlank(sort)) {
        params.add(CommonParams.SORT, sort);
    }
    params.add(CommonParams.FQ, StringUtils.defaultIfBlank(customFilter, "status:Approved"));
    return params;
}

From source file:org.phenotips.vocabulary.internal.solr.HumanPhenotypeOntology.java

License:Open Source License

private SolrParams produceDynamicSolrParams(String originalQuery, Integer rows, String sort, String customFq,
        boolean isId) {
    String query = originalQuery.trim();
    ModifiableSolrParams params = new ModifiableSolrParams();
    String escapedQuery = ClientUtils.escapeQueryChars(query);
    if (isId) {//from  w  w w .  ja  va 2 s .c o  m
        params.add(CommonParams.FQ, StringUtils.defaultIfBlank(customFq,
                new MessageFormat("id:{0} alt_id:{0}").format(new String[] { escapedQuery })));
    } else {
        params.add(CommonParams.FQ, StringUtils.defaultIfBlank(customFq, "term_category:HP\\:0000118"));
    }
    params.add(CommonParams.Q, escapedQuery);
    params.add(SpellingParams.SPELLCHECK_Q, query);
    params.add(CommonParams.ROWS, rows.toString());
    if (StringUtils.isNotBlank(sort)) {
        params.add(CommonParams.SORT, sort);
    }
    return params;
}