Java Code Examples for org.elasticsearch.common.regex.Regex#isSimpleMatchPattern()

The following examples show how to use org.elasticsearch.common.regex.Regex#isSimpleMatchPattern() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MultiMatchQueryParser.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private void extractFieldAndBoost(QueryParseContext parseContext, XContentParser parser, Map<String, Float> fieldNameWithBoosts) throws IOException {
    String fField = null;
    Float fBoost = null;
    char[] fieldText = parser.textCharacters();
    int end = parser.textOffset() + parser.textLength();
    for (int i = parser.textOffset(); i < end; i++) {
        if (fieldText[i] == '^') {
            int relativeLocation = i - parser.textOffset();
            fField = new String(fieldText, parser.textOffset(), relativeLocation);
            fBoost = Float.parseFloat(new String(fieldText, i + 1, parser.textLength() - relativeLocation - 1));
            break;
        }
    }
    if (fField == null) {
        fField = parser.text();
    }

    if (Regex.isSimpleMatchPattern(fField)) {
        for (String field : parseContext.mapperService().simpleMatchToIndexNames(fField)) {
            fieldNameWithBoosts.put(field, fBoost);
        }
    } else {
        fieldNameWithBoosts.put(fField, fBoost);
    }
}
 
Example 2
Source File: IndexNameExpressionResolver.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Identifies whether the first argument (an array containing index names) is a pattern that matches all indices
 *
 * @param indicesOrAliases the array containing index names
 * @param concreteIndices  array containing the concrete indices that the first argument refers to
 * @return true if the first argument is a pattern that maps to all available indices, false otherwise
 */
boolean isPatternMatchingAllIndices(MetaData metaData, String[] indicesOrAliases, String[] concreteIndices) {
    // if we end up matching on all indices, check, if its a wildcard parameter, or a "-something" structure
    if (concreteIndices.length == metaData.concreteAllIndices().length && indicesOrAliases.length > 0) {

        //we might have something like /-test1,+test1 that would identify all indices
        //or something like /-test1 with test1 index missing and IndicesOptions.lenient()
        if (indicesOrAliases[0].charAt(0) == '-') {
            return true;
        }

        //otherwise we check if there's any simple regex
        for (String indexOrAlias : indicesOrAliases) {
            if (Regex.isSimpleMatchPattern(indexOrAlias)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 3
Source File: SettingsFilter.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public static Settings filterSettings(String patterns, Settings settings) {
    String[] patternArray = Strings.delimitedListToStringArray(patterns, ",");
    Settings.Builder builder = Settings.settingsBuilder().put(settings);
    List<String> simpleMatchPatternList = new ArrayList<>();
    for (String pattern : patternArray) {
        if (Regex.isSimpleMatchPattern(pattern)) {
            simpleMatchPatternList.add(pattern);
        } else {
            builder.remove(pattern);
        }
    }
    if (!simpleMatchPatternList.isEmpty()) {
        String[] simpleMatchPatterns = simpleMatchPatternList.toArray(new String[simpleMatchPatternList.size()]);
        Iterator<Entry<String, String>> iterator = builder.internalMap().entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> current = iterator.next();
            if (Regex.simpleMatch(simpleMatchPatterns, current.getKey())) {
                iterator.remove();
            }
        }
    }
    return builder.build();
}
 
Example 4
Source File: TransportGetIndexTemplatesAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
protected void masterOperation(GetIndexTemplatesRequest request, ClusterState state, ActionListener<GetIndexTemplatesResponse> listener) {
    List<IndexTemplateMetaData> results;

    // If we did not ask for a specific name, then we return all templates
    if (request.names().length == 0) {
        results = Arrays.asList(state.metaData().templates().values().toArray(IndexTemplateMetaData.class));
    } else {
        results = new ArrayList<>();
    }

    for (String name : request.names()) {
        if (Regex.isSimpleMatchPattern(name)) {
            for (ObjectObjectCursor<String, IndexTemplateMetaData> entry : state.metaData().templates()) {
                if (Regex.simpleMatch(name, entry.key)) {
                    results.add(entry.value);
                }
            }
        } else if (state.metaData().templates().containsKey(name)) {
            results.add(state.metaData().templates().get(name));
        }
    }

    listener.onResponse(new GetIndexTemplatesResponse(results));
}
 
Example 5
Source File: IndexNameExpressionResolver.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Identifies whether the first argument (an array containing index names) is a pattern that matches all indices
 *
 * @param indicesOrAliases the array containing index names
 * @param concreteIndices  array containing the concrete indices that the first argument refers to
 * @return true if the first argument is a pattern that maps to all available indices, false otherwise
 */
boolean isPatternMatchingAllIndices(MetaData metaData, String[] indicesOrAliases, String[] concreteIndices) {
    // if we end up matching on all indices, check, if its a wildcard parameter, or a "-something" structure
    if (concreteIndices.length == metaData.getConcreteAllIndices().length && indicesOrAliases.length > 0) {

        //we might have something like /-test1,+test1 that would identify all indices
        //or something like /-test1 with test1 index missing and IndicesOptions.lenient()
        if (indicesOrAliases[0].charAt(0) == '-') {
            return true;
        }

        //otherwise we check if there's any simple regex
        for (String indexOrAlias : indicesOrAliases) {
            if (Regex.isSimpleMatchPattern(indexOrAlias)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 6
Source File: TransportGetIndexTemplatesAction.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
protected void masterOperation(GetIndexTemplatesRequest request, ClusterState state, ActionListener<GetIndexTemplatesResponse> listener) {
    List<IndexTemplateMetaData> results;

    // If we did not ask for a specific name, then we return all templates
    if (request.names().length == 0) {
        results = Arrays.asList(state.metaData().templates().values().toArray(IndexTemplateMetaData.class));
    } else {
        results = new ArrayList<>();
    }

    for (String name : request.names()) {
        if (Regex.isSimpleMatchPattern(name)) {
            for (ObjectObjectCursor<String, IndexTemplateMetaData> entry : state.metaData().templates()) {
                if (Regex.simpleMatch(name, entry.key)) {
                    results.add(entry.value);
                }
            }
        } else if (state.metaData().templates().containsKey(name)) {
            results.add(state.metaData().templates().get(name));
        }
    }

    listener.onResponse(new GetIndexTemplatesResponse(results));
}
 
Example 7
Source File: MapperService.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all the fields that match the given pattern. If the pattern is prefixed with a type
 * then the fields will be returned with a type prefix.
 */
public Collection<String> simpleMatchToIndexNames(String pattern) {
    if (Regex.isSimpleMatchPattern(pattern) == false) {
        // no wildcards
        return Collections.singletonList(pattern);
    }
    return fieldTypes.simpleMatchToIndexNames(pattern);
}
 
Example 8
Source File: RestTable.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts all the required fields from the RestRequest 'h' parameter. In order to support wildcards like
 * 'bulk.*' this needs potentially parse all the configured headers and its aliases and needs to ensure
 * that everything is only added once to the returned headers, even if 'h=bulk.*.bulk.*' is specified
 * or some headers are contained twice due to matching aliases
 */
private static Set<String> expandHeadersFromRequest(Table table, RestRequest request) {
    Set<String> headers = new LinkedHashSet<>(table.getHeaders().size());

    // check headers and aliases
    for (String header : Strings.splitStringByCommaToArray(request.param("h"))) {
        if (Regex.isSimpleMatchPattern(header)) {
            for (Table.Cell tableHeaderCell : table.getHeaders()) {
                String configuredHeader = tableHeaderCell.value.toString();
                if (Regex.simpleMatch(header, configuredHeader)) {
                    headers.add(configuredHeader);
                } else if (tableHeaderCell.attr.containsKey("alias")) {
                    String[] aliases = Strings.splitStringByCommaToArray(tableHeaderCell.attr.get("alias"));
                    for (String alias : aliases) {
                        if (Regex.simpleMatch(header, alias)) {
                            headers.add(configuredHeader);
                            break;
                        }
                    }
                }
            }
        } else {
            headers.add(header);
        }
    }

    return headers;
}
 
Example 9
Source File: QueryParserHelper.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve all the field names and patterns present in the provided map with the
 * {@link QueryShardContext} and returns a new map containing all the expanded fields with their original boost.
 * @param context The context of the query.
 * @param fieldsAndWeights The map of fields and weights to expand.
 * @param fieldSuffix The suffix name to add to the expanded field names if a mapping exists for that name.
 *                    The original name of the field is kept if adding the suffix to the field name does not point to a valid field
 *                    in the mapping.
 */
public static Map<String, Float> resolveMappingFields(QueryShardContext context,
                                                      Map<String, Float> fieldsAndWeights,
                                                      String fieldSuffix) {
    Map<String, Float> resolvedFields = new HashMap<>();
    for (Map.Entry<String, Float> fieldEntry : fieldsAndWeights.entrySet()) {
        boolean allField = Regex.isMatchAllPattern(fieldEntry.getKey());
        boolean multiField = Regex.isSimpleMatchPattern(fieldEntry.getKey());
        float weight = fieldEntry.getValue() == null ? 1.0f : fieldEntry.getValue();
        Map<String, Float> fieldMap = resolveMappingField(context, fieldEntry.getKey(), weight,
            !multiField, !allField, fieldSuffix);
        resolvedFields.putAll(fieldMap);
    }
    return resolvedFields;
}
 
Example 10
Source File: MapperService.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all the fields that match the given pattern. If the pattern is prefixed with a type
 * then the fields will be returned with a type prefix.
 */
public Collection<String> simpleMatchToFullName(String pattern) {
    if (Regex.isSimpleMatchPattern(pattern) == false) {
        // no wildcards
        return Collections.singletonList(pattern);
    }
    return fieldTypes.simpleMatchToFullName(pattern);
}
 
Example 11
Source File: MockLogAppender.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public void match(LogEvent event) {
    if (event.getLevel().equals(level) && event.getLoggerName().equals(logger) && innerMatch(event)) {
        if (Regex.isSimpleMatchPattern(message)) {
            if (Regex.simpleMatch(message, event.getMessage().getFormattedMessage())) {
                saw = true;
            }
        } else {
            if (event.getMessage().getFormattedMessage().contains(message)) {
                saw = true;
            }
        }
    }
}
 
Example 12
Source File: SnapshotUtils.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * Filters out list of available indices based on the list of selected indices.
 *
 * @param availableIndices list of available indices
 * @param selectedIndices  list of selected indices
 * @param indicesOptions    ignore indices flag
 * @return filtered out indices
 */
public static List<String> filterIndices(List<String> availableIndices, String[] selectedIndices, IndicesOptions indicesOptions) {
    if (selectedIndices == null || selectedIndices.length == 0) {
        return availableIndices;
    }
    Set<String> result = null;
    for (int i = 0; i < selectedIndices.length; i++) {
        String indexOrPattern = selectedIndices[i];
        boolean add = true;
        if (!indexOrPattern.isEmpty()) {
            if (availableIndices.contains(indexOrPattern)) {
                if (result == null) {
                    result = new HashSet<>();
                }
                result.add(indexOrPattern);
                continue;
            }
            if (indexOrPattern.charAt(0) == '+') {
                add = true;
                indexOrPattern = indexOrPattern.substring(1);
                // if its the first, add empty set
                if (i == 0) {
                    result = new HashSet<>();
                }
            } else if (indexOrPattern.charAt(0) == '-') {
                // if its the first, fill it with all the indices...
                if (i == 0) {
                    result = new HashSet<>(availableIndices);
                }
                add = false;
                indexOrPattern = indexOrPattern.substring(1);
            }
        }
        if (indexOrPattern.isEmpty() || !Regex.isSimpleMatchPattern(indexOrPattern)) {
            if (!availableIndices.contains(indexOrPattern)) {
                if (!indicesOptions.ignoreUnavailable()) {
                    throw new IndexNotFoundException(indexOrPattern);
                } else {
                    if (result == null) {
                        // add all the previous ones...
                        result = new HashSet<>();
                        result.addAll(availableIndices.subList(0, i));
                    }
                }
            } else {
                if (result != null) {
                    if (add) {
                        result.add(indexOrPattern);
                    } else {
                        result.remove(indexOrPattern);
                    }
                }
            }
            continue;
        }
        if (result == null) {
            // add all the previous ones...
            result = new HashSet<>();
            result.addAll(availableIndices.subList(0, i));
        }
        boolean found = false;
        for (String index : availableIndices) {
            if (Regex.simpleMatch(indexOrPattern, index)) {
                found = true;
                if (add) {
                    result.add(index);
                } else {
                    result.remove(index);
                }
            }
        }
        if (!found && !indicesOptions.allowNoIndices()) {
            throw new IndexNotFoundException(indexOrPattern);
        }
    }
    if (result == null) {
        return Collections.unmodifiableList(new ArrayList<>(Arrays.asList(selectedIndices)));
    }
    return Collections.unmodifiableList(new ArrayList<>(result));
}
 
Example 13
Source File: SnapshotUtils.java    From crate with Apache License 2.0 4 votes vote down vote up
/**
 * Filters out list of available indices based on the list of selected indices.
 *
 * @param availableIndices list of available indices
 * @param selectedIndices  list of selected indices
 * @param indicesOptions    ignore indices flag
 * @return filtered out indices
 */
public static List<String> filterIndices(List<String> availableIndices, String[] selectedIndices, IndicesOptions indicesOptions) {
    if (IndexNameExpressionResolver.isAllIndices(Arrays.asList(selectedIndices))) {
        return availableIndices;
    }
    Set<String> result = null;
    for (int i = 0; i < selectedIndices.length; i++) {
        String indexOrPattern = selectedIndices[i];
        boolean add = true;
        if (!indexOrPattern.isEmpty()) {
            if (availableIndices.contains(indexOrPattern)) {
                if (result == null) {
                    result = new HashSet<>();
                }
                result.add(indexOrPattern);
                continue;
            }
            if (indexOrPattern.charAt(0) == '+') {
                add = true;
                indexOrPattern = indexOrPattern.substring(1);
                // if its the first, add empty set
                if (i == 0) {
                    result = new HashSet<>();
                }
            } else if (indexOrPattern.charAt(0) == '-') {
                // if its the first, fill it with all the indices...
                if (i == 0) {
                    result = new HashSet<>(availableIndices);
                }
                add = false;
                indexOrPattern = indexOrPattern.substring(1);
            }
        }
        if (indexOrPattern.isEmpty() || !Regex.isSimpleMatchPattern(indexOrPattern)) {
            if (!availableIndices.contains(indexOrPattern)) {
                if (!indicesOptions.ignoreUnavailable()) {
                    throw new IndexNotFoundException(indexOrPattern);
                } else {
                    if (result == null) {
                        // add all the previous ones...
                        result = new HashSet<>(availableIndices.subList(0, i));
                    }
                }
            } else {
                if (result != null) {
                    if (add) {
                        result.add(indexOrPattern);
                    } else {
                        result.remove(indexOrPattern);
                    }
                }
            }
            continue;
        }
        if (result == null) {
            // add all the previous ones...
            result = new HashSet<>(availableIndices.subList(0, i));
        }
        boolean found = false;
        for (String index : availableIndices) {
            if (Regex.simpleMatch(indexOrPattern, index)) {
                found = true;
                if (add) {
                    result.add(index);
                } else {
                    result.remove(index);
                }
            }
        }
        if (!found && !indicesOptions.allowNoIndices()) {
            throw new IndexNotFoundException(indexOrPattern);
        }
    }
    if (result == null) {
        return Collections.unmodifiableList(new ArrayList<>(Arrays.asList(selectedIndices)));
    }
    return Collections.unmodifiableList(new ArrayList<>(result));
}