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.opencastproject.scheduler.impl.solr.SchedulerServiceSolrIndex.java

License:Educational Community License

/**
 * Appends query parameters to a solr query in a way that they are found even though they are not treated as a full
 * word in solr./*from   w ww .j ava  2 s .  c o  m*/
 * 
 * @param sb
 *          The {@link StringBuilder} containing the query
 * @param key
 *          the key for this search parameter
 * @param value
 *          the value for this search parameter
 * @return the appended {@link StringBuilder}
 */
private StringBuilder appendFuzzy(StringBuilder sb, String key, String value) {
    if (StringUtils.isBlank(key) || StringUtils.isBlank(value)) {
        return sb;
    }
    if (sb.length() > 0) {
        sb.append(" AND ");
    }
    sb.append("(");
    sb.append(key).append(":").append(ClientUtils.escapeQueryChars(value));
    sb.append(" OR ");
    sb.append(key).append(":*").append(ClientUtils.escapeQueryChars(value)).append("*");
    sb.append(")");
    return sb;
}

From source file:org.opencastproject.scheduler.impl.solr.SchedulerServiceSolrIndex.java

License:Educational Community License

/**
 * Builds a solr search query from a {@link org.opencastproject.series.api.SeriesQuery}.
 * /*from   w ww . j  av a 2  s. c  o  m*/
 * @param query
 *          the series query
 * @return the solr query string
 */
protected String buildSolrQueryString(SchedulerQuery query) {
    StringBuilder sb = new StringBuilder();
    append(sb, SolrFields.ID_KEY, query.getIdentifier());
    append(sb, SolrFields.IS_PART_OF_KEY, query.getSeriesId());
    appendFuzzy(sb, SolrFields.TITLE_KEY, query.getTitle());
    appendFuzzy(sb, SolrFields.FULLTEXT_KEY, query.getText());
    appendFuzzy(sb, SolrFields.CREATOR_KEY, query.getCreator());
    appendFuzzy(sb, SolrFields.CONTRIBUTOR_KEY, query.getContributor());
    append(sb, SolrFields.LANGUAGE_KEY, query.getLanguage());
    append(sb, SolrFields.LICENSE_KEY, query.getLicense());
    appendFuzzy(sb, SolrFields.SUBJECT_KEY, query.getSubject());
    appendFuzzy(sb, SolrFields.ABSTRACT_KEY, query.getAbstract());
    appendFuzzy(sb, SolrFields.DESCRIPTION_KEY, query.getDescription());
    appendFuzzy(sb, SolrFields.PUBLISHER_KEY, query.getPublisher());
    append(sb, SolrFields.SPATIAL_KEY, query.getSpatial());
    appendFuzzy(sb, SolrFields.RIGHTS_HOLDER_KEY, query.getRightsHolder());
    appendFuzzy(sb, SolrFields.SUBJECT_KEY, query.getSubject());
    append(sb, SolrFields.CREATED_KEY, query.getCreatedFrom(), query.getCreatedTo());
    append(sb, SolrFields.STARTS_KEY, query.getStartsFrom(), query.getStartsTo());
    append(sb, SolrFields.ENDS_KEY, query.getEndsFrom(), query.getEndsTo());

    if (query.getIdsList() != null) {
        if (sb.length() > 0) {
            sb.append(" AND ");
        }
        sb.append("(");
        List<Long> ids = query.getIdsList();
        for (int i = 0; i < ids.size(); i++) {
            String id = Long.toString(ids.get(i));
            if (StringUtils.isNotEmpty(id)) {
                sb.append(SolrFields.ID_KEY);
                sb.append(":");
                sb.append(ClientUtils.escapeQueryChars(id));
            }
            if (i < ids.size() - 1) {
                sb.append(" OR ");
            }
        }
        sb.append(")");
    }

    // If we're looking for anything, set the query to a wildcard search
    if (sb.length() == 0) {
        sb.append("*:*");
    }

    logger.debug("Solr query: " + sb.toString());
    return sb.toString();
}

From source file:org.opencastproject.search.impl.solr.SolrIndexManager.java

License:Educational Community License

/**
 * Removes the entry with the given <code>id</code> from the database. The entry can either be a series or an episode.
 * //from www .  j av  a2 s . com
 * @param id
 *          identifier of the series or episode to delete
 * @param deletionDate
 *          the deletion date
 * @throws SolrServerException
 *           if an errors occurs while talking to solr
 */
public boolean delete(String id, Date deletionDate) throws SolrServerException {
    try {
        // Load the existing episode
        QueryResponse solrResponse = null;
        try {
            SolrQuery query = new SolrQuery(Schema.ID + ":" + ClientUtils.escapeQueryChars(id) + " AND -"
                    + Schema.OC_DELETED + ":[* TO *]");
            solrResponse = solrServer.query(query);
        } catch (Exception e1) {
            throw new SolrServerException(e1);
        }

        // Did we find the episode?
        if (solrResponse.getResults().size() == 0) {
            logger.warn("Trying to delete non-existing media package {} from the search index", id);
            return false;
        }

        // Use all existing fields
        SolrDocument doc = solrResponse.getResults().get(0);
        SolrInputDocument inputDocument = new SolrInputDocument();
        for (String field : doc.getFieldNames()) {
            inputDocument.setField(field, doc.get(field));
        }

        // Set the oc_deleted field to the current date, then update
        Schema.setOcDeleted(inputDocument, deletionDate);
        solrServer.add(inputDocument);
        solrServer.commit();
        return true;
    } catch (IOException e) {
        throw new SolrServerException(e);
    }
}

From source file:org.opencastproject.series.impl.solr.SeriesServiceSolrIndex.java

License:Educational Community License

/**
 * Creates solr document for inserting into solr index.
 * /*  w w w  .ja  va 2s  . c o m*/
 * @param dc
 *          {@link DublinCoreCatalog} to be stored in index
 * @return {@link SolrInputDocument} created out of Dublin core
 */
protected SolrInputDocument createDocument(DublinCoreCatalog dc) {
    final SolrInputDocument doc = new SolrInputDocument();
    String dublinCoreId = dc.getFirst(DublinCore.PROPERTY_IDENTIFIER);
    String orgId = securityService.getOrganization().getId();
    doc.addField(SolrFields.COMPOSITE_ID_KEY, getCompositeKey(dublinCoreId, orgId));
    doc.addField(SolrFields.ORGANIZATION, ClientUtils.escapeQueryChars(orgId));
    try {
        doc.addField(SolrFields.XML_KEY, serializeDublinCore(dc));
    } catch (IOException e1) {
        throw new IllegalArgumentException(e1);
    }

    // single valued fields
    if (dc.hasValue(DublinCore.PROPERTY_TITLE)) {
        doc.addField(SolrFields.TITLE_KEY, dc.getFirst(DublinCore.PROPERTY_TITLE));
        doc.addField(SolrFields.TITLE_KEY + "_sort", dc.getFirst(DublinCore.PROPERTY_TITLE));
    }
    if (dc.hasValue(DublinCore.PROPERTY_CREATED)) {
        final Temporal temporal = EncodingSchemeUtils
                .decodeTemporal(dc.get(DublinCore.PROPERTY_CREATED).get(0));
        temporal.fold(new Temporal.Match<Void>() {
            @Override
            public Void period(DCMIPeriod period) {
                doc.addField(SolrFields.CREATED_KEY, period.getStart());
                return null;
            }

            @Override
            public Void instant(Date instant) {
                doc.addField(SolrFields.CREATED_KEY, instant);
                return null;
            }

            @Override
            public Void duration(long duration) {
                throw new IllegalArgumentException("Dublin core dc:created is neither a date nor a period");
            }
        });
    }
    if (dc.hasValue(DublinCore.PROPERTY_AVAILABLE)) {
        Temporal temporal = EncodingSchemeUtils.decodeTemporal(dc.get(DublinCore.PROPERTY_AVAILABLE).get(0));
        temporal.fold(new Temporal.Match<Void>() {
            @Override
            public Void period(DCMIPeriod period) {
                if (period.hasStart()) {
                    doc.addField(SolrFields.AVAILABLE_FROM_KEY, period.getStart());
                }
                if (period.hasEnd()) {
                    doc.addField(SolrFields.AVAILABLE_TO_KEY, period.getEnd());
                }
                return null;
            }

            @Override
            public Void instant(Date instant) {
                doc.addField(SolrFields.AVAILABLE_FROM_KEY, instant);
                return null;
            }

            @Override
            public Void duration(long duration) {
                throw new IllegalArgumentException(
                        "Dublin core field dc:available is neither a date nor a period");
            }
        });
    }

    // multivalued fields
    addMultiValuedFieldToSolrDocument(doc, SolrFields.SUBJECT_KEY, dc.get(DublinCore.PROPERTY_SUBJECT));
    addMultiValuedFieldToSolrDocument(doc, SolrFields.CREATOR_KEY, dc.get(DublinCore.PROPERTY_CREATOR));
    addMultiValuedFieldToSolrDocument(doc, SolrFields.PUBLISHER_KEY, dc.get(DublinCore.PROPERTY_PUBLISHER));
    addMultiValuedFieldToSolrDocument(doc, SolrFields.CONTRIBUTOR_KEY, dc.get(DublinCore.PROPERTY_CONTRIBUTOR));
    addMultiValuedFieldToSolrDocument(doc, SolrFields.ABSTRACT_KEY, dc.get(DublinCore.PROPERTY_ABSTRACT));
    addMultiValuedFieldToSolrDocument(doc, SolrFields.DESCRIPTION_KEY, dc.get(DublinCore.PROPERTY_DESCRIPTION));
    addMultiValuedFieldToSolrDocument(doc, SolrFields.LANGUAGE_KEY, dc.get(DublinCore.PROPERTY_LANGUAGE));
    addMultiValuedFieldToSolrDocument(doc, SolrFields.RIGHTS_HOLDER_KEY,
            dc.get(DublinCore.PROPERTY_RIGHTS_HOLDER));
    addMultiValuedFieldToSolrDocument(doc, SolrFields.SPATIAL_KEY, dc.get(DublinCore.PROPERTY_SPATIAL));
    addMultiValuedFieldToSolrDocument(doc, SolrFields.TEMPORAL_KEY, dc.get(DublinCore.PROPERTY_TEMPORAL));
    addMultiValuedFieldToSolrDocument(doc, SolrFields.IS_PART_OF_KEY, dc.get(DublinCore.PROPERTY_IS_PART_OF));
    addMultiValuedFieldToSolrDocument(doc, SolrFields.REPLACES_KEY, dc.get(DublinCore.PROPERTY_REPLACES));
    addMultiValuedFieldToSolrDocument(doc, SolrFields.TYPE_KEY, dc.get(DublinCore.PROPERTY_TYPE));
    addMultiValuedFieldToSolrDocument(doc, SolrFields.ACCESS_RIGHTS_KEY,
            dc.get(DublinCore.PROPERTY_ACCESS_RIGHTS));
    addMultiValuedFieldToSolrDocument(doc, SolrFields.LICENSE_KEY, dc.get(DublinCore.PROPERTY_LICENSE));

    return doc;
}

From source file:org.opencastproject.series.impl.solr.SeriesServiceSolrIndex.java

License:Educational Community License

/**
 * Appends query parameters to a solr query
 * //from   w ww .  java2 s . c  om
 * @param sb
 *          The {@link StringBuilder} containing the query
 * @param key
 *          the key for this search parameter
 * @param value
 *          the value for this search parameter
 * @return the appended {@link StringBuilder}
 */
private StringBuilder appendAnd(StringBuilder sb, String key, String value) {
    if (StringUtils.isBlank(key) || StringUtils.isBlank(value)) {
        return sb;
    }
    if (sb.length() > 0) {
        sb.append(" AND ");
    }
    sb.append(key);
    sb.append(":");
    sb.append(ClientUtils.escapeQueryChars(value));
    return sb;
}

From source file:org.opencastproject.series.impl.solr.SeriesServiceSolrIndex.java

License:Educational Community License

private StringBuilder append(StringBuilder sb, String bool, String key, String[] values) {
    if (StringUtils.isBlank(key) || values.length == 0) {
        return sb;
    }//from w w  w.j  a v a  2  s  .com
    if (sb.length() > 0) {
        sb.append(" ").append(bool).append(" (");
    }
    for (int i = 0; i < values.length; i++) {
        if (i > 0) {
            sb.append(" OR ");
        }
        sb.append(key);
        sb.append(":");
        sb.append(ClientUtils.escapeQueryChars(values[i]));
    }
    sb.append(")");
    return sb;
}

From source file:org.opencastproject.series.impl.solr.SeriesServiceSolrIndex.java

License:Educational Community License

/**
 * Returns SolrDocument corresponding to given ID or null if such document does not exist.
 * //from   w  w w . j  av  a2  s.co  m
 * @param id
 *          SolrDocument ID
 * @return corresponding document
 * @throws SeriesServiceDatabaseException
 *           if exception occurred
 */
protected SolrDocument getSolrDocumentByID(String id) throws SeriesServiceDatabaseException {
    String orgId = securityService.getOrganization().getId();
    StringBuilder solrQueryString = new StringBuilder(SolrFields.COMPOSITE_ID_KEY).append(":")
            .append(ClientUtils.escapeQueryChars(getCompositeKey(id, orgId)));

    SolrQuery q = new SolrQuery(solrQueryString.toString());
    QueryResponse response;
    try {
        response = solrServer.query(q);
        if (response.getResults().isEmpty()) {
            return null;
        } else {
            return response.getResults().get(0);
        }
    } catch (SolrServerException e) {
        logger.error("Could not perform series retrieval: {}", e);
        throw new SeriesServiceDatabaseException(e);
    }
}

From source file:org.opencms.jsp.search.controller.CmsSearchControllerCommon.java

License:Open Source License

/**
 * @see org.opencms.jsp.search.controller.I_CmsSearchController#addQueryParts(CmsSolrQuery)
 *//*from  ww w. jav  a2 s .com*/
@Override
public void addQueryParts(CmsSolrQuery query) {

    String queryString = m_state.getQuery();
    if (!m_config.getIgnoreQueryParam()) {
        if (m_config.getEscapeQueryChars()) {
            queryString = ClientUtils.escapeQueryChars(queryString);
        }
        if (queryString.isEmpty() && m_config.getSearchForEmptyQueryParam()) {
            queryString = "*";
        }
        String modifiedQuery = m_config.getModifiedQuery(queryString);
        if (modifiedQuery.startsWith("{!")) {
            modifiedQuery = "{!tag=q " + modifiedQuery.substring(2);
        } else {
            modifiedQuery = "{!tag=q}" + modifiedQuery;
        }
        query.set("q", modifiedQuery);
    }

    if (m_config.getSolrIndex() != null) {
        query.set("index", m_config.getSolrIndex());
    }
    if (m_config.getSolrCore() != null) {
        query.set("core", m_config.getSolrCore());
    }

    if (!m_config.getExtraSolrParams().isEmpty()) {
        Map<String, String[]> extraParamsMap = CmsRequestUtil.createParameterMap(m_config.getExtraSolrParams());
        for (String key : extraParamsMap.keySet()) {
            for (String value : Arrays.asList(extraParamsMap.get(key))) {
                if (SET_VARIABLES.contains(key)) {
                    query.set(key, value);
                } else {
                    query.add(key, value);
                }
            }
        }
    }
    for (String additionalParam : m_state.getAdditionalParameters().keySet()) {
        String additionalParamString = resolveMacros(m_config.getAdditionalParameters().get(additionalParam),
                m_state.getAdditionalParameters().get(additionalParam));
        Map<String, String[]> extraParamsMap = CmsRequestUtil.createParameterMap(additionalParamString);
        for (String key : extraParamsMap.keySet()) {
            for (String value : Arrays.asList(extraParamsMap.get(key))) {
                if (SET_VARIABLES.contains(key)) {
                    query.set(key, value);
                } else {
                    query.add(key, value);
                }
            }
        }
    }
}

From source file:org.opencommercesearch.RuleManager.java

License:Apache License

/**
 * Gets the target filter//from  w  w w.j a v a 2  s . co  m
 * @param reusableStringBuilder String builder to put data into
 * @return Target filter for rules
 */
private String getTargetFilter(StringBuilder reusableStringBuilder, boolean isSearch, String q) {
    StringBuilder targetFilter = reuseStringBuilder(reusableStringBuilder);

    if (isSearch) {
        targetFilter.append("(target:allpages OR target:searchpages) AND ((");
        targetFilter.append(ClientUtils.escapeQueryChars(q.toLowerCase()));
        targetFilter.append(")^2 OR query:__all__)");
    } else {
        targetFilter.append("target:allpages OR target:categorypages");
    }

    return targetFilter.toString();
}

From source file:org.opencommercesearch.RulesBuilderTest.java

License:Apache License

@Test
public void testBuildComplexKeywordRule() throws RepositoryException {

    List<RepositoryItem> expresionList = new ArrayList<RepositoryItem>();
    String keyword = "this is a big weird keyword'";
    expresionList.add(mockRule("keyword", 1, keyword, null));
    mockBaseRule(productCatalog, expresionList, mock(RepositoryItem.class), "ruleCategory", true);

    String builder = rulesBuilder.buildRulesFilter("ruleCategory", Locale.US);

    assertEquals("(ancestorCategoryId:ruleCategory) OR (keyword:" + ClientUtils.escapeQueryChars(keyword) + ")",
            builder);/* w  ww .  j av a  2s.com*/
}