Search in sources :

Example 1 with MapperRegistry

use of org.opensearch.indices.mapper.MapperRegistry in project OpenSearch by opensearch-project.

the class IndicesModuleTests method testGetFieldFilter.

public void testGetFieldFilter() {
    List<MapperPlugin> mapperPlugins = Arrays.asList(new MapperPlugin() {

        @Override
        public Function<String, Predicate<String>> getFieldFilter() {
            return MapperPlugin.NOOP_FIELD_FILTER;
        }
    }, new MapperPlugin() {

        @Override
        public Function<String, Predicate<String>> getFieldFilter() {
            return index -> index.equals("hidden_index") ? field -> false : MapperPlugin.NOOP_FIELD_PREDICATE;
        }
    }, new MapperPlugin() {

        @Override
        public Function<String, Predicate<String>> getFieldFilter() {
            return index -> field -> field.equals("hidden_field") == false;
        }
    }, new MapperPlugin() {

        @Override
        public Function<String, Predicate<String>> getFieldFilter() {
            return index -> index.equals("filtered") ? field -> field.equals("visible") : MapperPlugin.NOOP_FIELD_PREDICATE;
        }
    });
    IndicesModule indicesModule = new IndicesModule(mapperPlugins);
    MapperRegistry mapperRegistry = indicesModule.getMapperRegistry();
    Function<String, Predicate<String>> fieldFilter = mapperRegistry.getFieldFilter();
    assertNotSame(MapperPlugin.NOOP_FIELD_FILTER, fieldFilter);
    assertFalse(fieldFilter.apply("hidden_index").test(randomAlphaOfLengthBetween(3, 5)));
    assertTrue(fieldFilter.apply(randomAlphaOfLengthBetween(3, 5)).test(randomAlphaOfLengthBetween(3, 5)));
    assertFalse(fieldFilter.apply(randomAlphaOfLengthBetween(3, 5)).test("hidden_field"));
    assertFalse(fieldFilter.apply("filtered").test(randomAlphaOfLengthBetween(3, 5)));
    assertFalse(fieldFilter.apply("filtered").test("hidden_field"));
    assertTrue(fieldFilter.apply("filtered").test("visible"));
    assertFalse(fieldFilter.apply("hidden_index").test("visible"));
    assertTrue(fieldFilter.apply(randomAlphaOfLengthBetween(3, 5)).test("visible"));
    assertFalse(fieldFilter.apply("hidden_index").test("hidden_field"));
}
Also used : IdFieldMapper(org.opensearch.index.mapper.IdFieldMapper) Arrays(java.util.Arrays) IgnoredFieldMapper(org.opensearch.index.mapper.IgnoredFieldMapper) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) MapperPlugin(org.opensearch.plugins.MapperPlugin) Version(org.opensearch.Version) Function(java.util.function.Function) ArrayList(java.util.ArrayList) AllFieldMapper(org.opensearch.index.mapper.AllFieldMapper) DataStreamFieldMapper(org.opensearch.index.mapper.DataStreamFieldMapper) MapperRegistry(org.opensearch.indices.mapper.MapperRegistry) VersionUtils(org.opensearch.test.VersionUtils) Map(java.util.Map) VersionFieldMapper(org.opensearch.index.mapper.VersionFieldMapper) IndexFieldMapper(org.opensearch.index.mapper.IndexFieldMapper) Iterator(java.util.Iterator) Predicate(java.util.function.Predicate) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Set(java.util.Set) FieldNamesFieldMapper(org.opensearch.index.mapper.FieldNamesFieldMapper) Mapper(org.opensearch.index.mapper.Mapper) SourceFieldMapper(org.opensearch.index.mapper.SourceFieldMapper) TypeFieldMapper(org.opensearch.index.mapper.TypeFieldMapper) List(java.util.List) TextFieldMapper(org.opensearch.index.mapper.TextFieldMapper) MetadataFieldMapper(org.opensearch.index.mapper.MetadataFieldMapper) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) RoutingFieldMapper(org.opensearch.index.mapper.RoutingFieldMapper) Collections(java.util.Collections) Matchers.containsString(org.hamcrest.Matchers.containsString) SeqNoFieldMapper(org.opensearch.index.mapper.SeqNoFieldMapper) Function(java.util.function.Function) MapperPlugin(org.opensearch.plugins.MapperPlugin) MapperRegistry(org.opensearch.indices.mapper.MapperRegistry) Matchers.containsString(org.hamcrest.Matchers.containsString) Predicate(java.util.function.Predicate)

Example 2 with MapperRegistry

use of org.opensearch.indices.mapper.MapperRegistry in project OpenSearch by opensearch-project.

the class IndicesModuleTests method testBuiltinWithPlugins.

public void testBuiltinWithPlugins() {
    IndicesModule noPluginsModule = new IndicesModule(Collections.emptyList());
    IndicesModule module = new IndicesModule(fakePlugins);
    MapperRegistry registry = module.getMapperRegistry();
    assertThat(registry.getMapperParsers().size(), greaterThan(noPluginsModule.getMapperRegistry().getMapperParsers().size()));
    assertThat(registry.getMetadataMapperParsers(Version.CURRENT).size(), greaterThan(noPluginsModule.getMapperRegistry().getMetadataMapperParsers(Version.CURRENT).size()));
    Map<String, MetadataFieldMapper.TypeParser> metadataMapperParsers = module.getMapperRegistry().getMetadataMapperParsers(Version.CURRENT);
    Iterator<String> iterator = metadataMapperParsers.keySet().iterator();
    assertEquals(IgnoredFieldMapper.NAME, iterator.next());
    String last = null;
    while (iterator.hasNext()) {
        last = iterator.next();
    }
    assertEquals(FieldNamesFieldMapper.NAME, last);
}
Also used : MapperRegistry(org.opensearch.indices.mapper.MapperRegistry) Matchers.containsString(org.hamcrest.Matchers.containsString)

Example 3 with MapperRegistry

use of org.opensearch.indices.mapper.MapperRegistry in project OpenSearch by opensearch-project.

the class AggregatorTestCase method testSupportedFieldTypes.

/**
 * This test will validate that an aggregator succeeds or fails to run against all the field types
 * that are registered in {@link IndicesModule} (e.g. all the core field types).  An aggregator
 * is provided by the implementor class, and it is executed against each field type in turn.  If
 * an exception is thrown when the field is supported, that will fail the test.  Similarly, if
 * an exception _is not_ thrown when a field is unsupported, that will also fail the test.
 *
 * Exception types/messages are not currently checked, just presence/absence of an exception.
 */
public void testSupportedFieldTypes() throws IOException {
    MapperRegistry mapperRegistry = new IndicesModule(Collections.emptyList()).getMapperRegistry();
    Settings settings = Settings.builder().put("index.version.created", Version.CURRENT.id).build();
    String fieldName = "typeTestFieldName";
    List<ValuesSourceType> supportedVSTypes = getSupportedValuesSourceTypes();
    List<String> unsupportedMappedFieldTypes = unsupportedMappedFieldTypes();
    if (supportedVSTypes.isEmpty()) {
        // If the test says it doesn't support any VStypes, it has not been converted yet so skip
        return;
    }
    for (Map.Entry<String, Mapper.TypeParser> mappedType : mapperRegistry.getMapperParsers().entrySet()) {
        // Some field types should not be tested, or require more work and are not ready yet
        if (TYPE_TEST_DENYLIST.contains(mappedType.getKey())) {
            continue;
        }
        Map<String, Object> source = new HashMap<>();
        source.put("type", mappedType.getKey());
        // Text is the only field that doesn't support DVs, instead FD
        if (mappedType.getKey().equals(TextFieldMapper.CONTENT_TYPE) == false) {
            source.put("doc_values", "true");
        }
        Mapper.Builder builder = mappedType.getValue().parse(fieldName, source, new MockParserContext());
        FieldMapper mapper = (FieldMapper) builder.build(new BuilderContext(settings, new ContentPath()));
        MappedFieldType fieldType = mapper.fieldType();
        // Non-aggregatable fields are not testable (they will throw an error on all aggs anyway), so skip
        if (fieldType.isAggregatable() == false) {
            continue;
        }
        try (Directory directory = newDirectory()) {
            RandomIndexWriter indexWriter = new RandomIndexWriter(random(), directory);
            writeTestDoc(fieldType, fieldName, indexWriter);
            indexWriter.close();
            try (IndexReader indexReader = DirectoryReader.open(directory)) {
                IndexSearcher indexSearcher = newIndexSearcher(indexReader);
                AggregationBuilder aggregationBuilder = createAggBuilderForTypeTest(fieldType, fieldName);
                ValuesSourceType vst = fieldToVST(fieldType);
                // TODO in the future we can make this more explicit with expectThrows(), when the exceptions are standardized
                AssertionError failure = null;
                try {
                    searchAndReduce(indexSearcher, new MatchAllDocsQuery(), aggregationBuilder, fieldType);
                    if (supportedVSTypes.contains(vst) == false || unsupportedMappedFieldTypes.contains(fieldType.typeName())) {
                        failure = new AssertionError("Aggregator [" + aggregationBuilder.getType() + "] should not support field type [" + fieldType.typeName() + "] but executing against the field did not throw an exception");
                    }
                } catch (Exception | AssertionError e) {
                    if (supportedVSTypes.contains(vst) && unsupportedMappedFieldTypes.contains(fieldType.typeName()) == false) {
                        failure = new AssertionError("Aggregator [" + aggregationBuilder.getType() + "] supports field type [" + fieldType.typeName() + "] but executing against the field threw an exception: [" + e.getMessage() + "]", e);
                    }
                }
                if (failure != null) {
                    throw failure;
                }
            }
        }
    }
}
Also used : AssertingIndexSearcher(org.apache.lucene.search.AssertingIndexSearcher) ContextIndexSearcher(org.opensearch.search.internal.ContextIndexSearcher) IndexSearcher(org.apache.lucene.search.IndexSearcher) IndicesModule(org.opensearch.indices.IndicesModule) NestedAggregationBuilder(org.opensearch.search.aggregations.bucket.nested.NestedAggregationBuilder) HashMap(java.util.HashMap) Mockito.anyString(org.mockito.Mockito.anyString) KeywordFieldMapper(org.opensearch.index.mapper.KeywordFieldMapper) FieldAliasMapper(org.opensearch.index.mapper.FieldAliasMapper) GeoPointFieldMapper(org.opensearch.index.mapper.GeoPointFieldMapper) RangeFieldMapper(org.opensearch.index.mapper.RangeFieldMapper) GeoShapeFieldMapper(org.opensearch.index.mapper.GeoShapeFieldMapper) TextFieldMapper(org.opensearch.index.mapper.TextFieldMapper) CompletionFieldMapper(org.opensearch.index.mapper.CompletionFieldMapper) ObjectMapper(org.opensearch.index.mapper.ObjectMapper) BinaryFieldMapper(org.opensearch.index.mapper.BinaryFieldMapper) NumberFieldMapper(org.opensearch.index.mapper.NumberFieldMapper) FieldMapper(org.opensearch.index.mapper.FieldMapper) Mapper(org.opensearch.index.mapper.Mapper) DateFieldMapper(org.opensearch.index.mapper.DateFieldMapper) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings) Directory(org.apache.lucene.store.Directory) CoreValuesSourceType(org.opensearch.search.aggregations.support.CoreValuesSourceType) ValuesSourceType(org.opensearch.search.aggregations.support.ValuesSourceType) ContentPath(org.opensearch.index.mapper.ContentPath) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) IOException(java.io.IOException) MapperRegistry(org.opensearch.indices.mapper.MapperRegistry) IndexReader(org.apache.lucene.index.IndexReader) BuilderContext(org.opensearch.index.mapper.Mapper.BuilderContext) Map(java.util.Map) HashMap(java.util.HashMap) Collections.singletonMap(java.util.Collections.singletonMap) Collections.emptyMap(java.util.Collections.emptyMap) KeywordFieldMapper(org.opensearch.index.mapper.KeywordFieldMapper) GeoPointFieldMapper(org.opensearch.index.mapper.GeoPointFieldMapper) RangeFieldMapper(org.opensearch.index.mapper.RangeFieldMapper) GeoShapeFieldMapper(org.opensearch.index.mapper.GeoShapeFieldMapper) TextFieldMapper(org.opensearch.index.mapper.TextFieldMapper) CompletionFieldMapper(org.opensearch.index.mapper.CompletionFieldMapper) BinaryFieldMapper(org.opensearch.index.mapper.BinaryFieldMapper) NumberFieldMapper(org.opensearch.index.mapper.NumberFieldMapper) FieldMapper(org.opensearch.index.mapper.FieldMapper) DateFieldMapper(org.opensearch.index.mapper.DateFieldMapper) RandomIndexWriter(org.apache.lucene.index.RandomIndexWriter)

Example 4 with MapperRegistry

use of org.opensearch.indices.mapper.MapperRegistry in project OpenSearch by opensearch-project.

the class MetadataIndexUpgradeService method checkMappingsCompatibility.

/**
 * Checks the mappings for compatibility with the current version
 */
private void checkMappingsCompatibility(IndexMetadata indexMetadata) {
    try {
        // We cannot instantiate real analysis server or similarity service at this point because the node
        // might not have been started yet. However, we don't really need real analyzers or similarities at
        // this stage - so we can fake it using constant maps accepting every key.
        // This is ok because all used similarities and analyzers for this index were known before the upgrade.
        // Missing analyzers and similarities plugin will still trigger the appropriate error during the
        // actual upgrade.
        IndexSettings indexSettings = new IndexSettings(indexMetadata, this.settings);
        final Map<String, TriFunction<Settings, Version, ScriptService, Similarity>> similarityMap = new AbstractMap<String, TriFunction<Settings, Version, ScriptService, Similarity>>() {

            @Override
            public boolean containsKey(Object key) {
                return true;
            }

            @Override
            public TriFunction<Settings, Version, ScriptService, Similarity> get(Object key) {
                assert key instanceof String : "key must be a string but was: " + key.getClass();
                return (settings, version, scriptService) -> new BM25Similarity();
            }

            // this entrySet impl isn't fully correct but necessary as SimilarityService will iterate
            // over all similarities
            @Override
            public Set<Entry<String, TriFunction<Settings, Version, ScriptService, Similarity>>> entrySet() {
                return Collections.emptySet();
            }
        };
        SimilarityService similarityService = new SimilarityService(indexSettings, null, similarityMap);
        final NamedAnalyzer fakeDefault = new NamedAnalyzer("default", AnalyzerScope.INDEX, new Analyzer() {

            @Override
            protected TokenStreamComponents createComponents(String fieldName) {
                throw new UnsupportedOperationException("shouldn't be here");
            }
        });
        final Map<String, NamedAnalyzer> analyzerMap = new AbstractMap<String, NamedAnalyzer>() {

            @Override
            public NamedAnalyzer get(Object key) {
                assert key instanceof String : "key must be a string but was: " + key.getClass();
                return new NamedAnalyzer((String) key, AnalyzerScope.INDEX, fakeDefault.analyzer());
            }

            // this entrySet impl isn't fully correct but necessary as IndexAnalyzers will iterate
            // over all analyzers to close them
            @Override
            public Set<Entry<String, NamedAnalyzer>> entrySet() {
                return Collections.emptySet();
            }
        };
        try (IndexAnalyzers fakeIndexAnalzyers = new IndexAnalyzers(analyzerMap, analyzerMap, analyzerMap)) {
            MapperService mapperService = new MapperService(indexSettings, fakeIndexAnalzyers, xContentRegistry, similarityService, mapperRegistry, () -> null, () -> false, scriptService);
            mapperService.merge(indexMetadata, MapperService.MergeReason.MAPPING_RECOVERY);
        }
    } catch (Exception ex) {
        // Wrap the inner exception so we have the index name in the exception message
        throw new IllegalStateException("unable to upgrade the mappings for the index [" + indexMetadata.getIndex() + "]", ex);
    }
}
Also used : ScriptService(org.opensearch.script.ScriptService) NamedAnalyzer(org.opensearch.index.analysis.NamedAnalyzer) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) SimilarityService(org.opensearch.index.similarity.SimilarityService) Analyzer(org.apache.lucene.analysis.Analyzer) Set(java.util.Set) Version(org.opensearch.Version) Settings(org.opensearch.common.settings.Settings) AnalyzerScope(org.opensearch.index.analysis.AnalyzerScope) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) SystemIndices(org.opensearch.indices.SystemIndices) AbstractMap(java.util.AbstractMap) Logger(org.apache.logging.log4j.Logger) MapperService(org.opensearch.index.mapper.MapperService) MapperRegistry(org.opensearch.indices.mapper.MapperRegistry) Similarity(org.apache.lucene.search.similarities.Similarity) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) Map(java.util.Map) IndexSettings(org.opensearch.index.IndexSettings) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) BM25Similarity(org.apache.lucene.search.similarities.BM25Similarity) IndexAnalyzers(org.opensearch.index.analysis.IndexAnalyzers) TriFunction(org.opensearch.common.TriFunction) Similarity(org.apache.lucene.search.similarities.Similarity) BM25Similarity(org.apache.lucene.search.similarities.BM25Similarity) NamedAnalyzer(org.opensearch.index.analysis.NamedAnalyzer) IndexSettings(org.opensearch.index.IndexSettings) NamedAnalyzer(org.opensearch.index.analysis.NamedAnalyzer) Analyzer(org.apache.lucene.analysis.Analyzer) AbstractMap(java.util.AbstractMap) ScriptService(org.opensearch.script.ScriptService) Version(org.opensearch.Version) SimilarityService(org.opensearch.index.similarity.SimilarityService) BM25Similarity(org.apache.lucene.search.similarities.BM25Similarity) TriFunction(org.opensearch.common.TriFunction) IndexAnalyzers(org.opensearch.index.analysis.IndexAnalyzers) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings) MapperService(org.opensearch.index.mapper.MapperService)

Example 5 with MapperRegistry

use of org.opensearch.indices.mapper.MapperRegistry in project OpenSearch by opensearch-project.

the class MapperServiceTestCase method createMapperService.

/**
 * Create a {@link MapperService} like we would for an index.
 */
protected final MapperService createMapperService(Version version, XContentBuilder mapping) throws IOException {
    IndexMetadata meta = IndexMetadata.builder("index").settings(Settings.builder().put("index.version.created", version)).numberOfReplicas(0).numberOfShards(1).build();
    IndexSettings indexSettings = new IndexSettings(meta, getIndexSettings());
    MapperRegistry mapperRegistry = new IndicesModule(getPlugins().stream().filter(p -> p instanceof MapperPlugin).map(p -> (MapperPlugin) p).collect(toList())).getMapperRegistry();
    ScriptModule scriptModule = new ScriptModule(Settings.EMPTY, getPlugins().stream().filter(p -> p instanceof ScriptPlugin).map(p -> (ScriptPlugin) p).collect(toList()));
    ScriptService scriptService = new ScriptService(getIndexSettings(), scriptModule.engines, scriptModule.contexts);
    SimilarityService similarityService = new SimilarityService(indexSettings, scriptService, emptyMap());
    MapperService mapperService = new MapperService(indexSettings, createIndexAnalyzers(indexSettings), xContentRegistry(), similarityService, mapperRegistry, () -> {
        throw new UnsupportedOperationException();
    }, () -> true, scriptService);
    merge(mapperService, mapping);
    return mapperService;
}
Also used : IndicesModule(org.opensearch.indices.IndicesModule) BytesReference(org.opensearch.common.bytes.BytesReference) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ScriptModule(org.opensearch.script.ScriptModule) SimilarityService(org.opensearch.index.similarity.SimilarityService) ToXContent(org.opensearch.common.xcontent.ToXContent) CheckedConsumer(org.opensearch.common.CheckedConsumer) CompressedXContent(org.opensearch.common.compress.CompressedXContent) MapperPlugin(org.opensearch.plugins.MapperPlugin) Version(org.opensearch.Version) AnalyzerScope(org.opensearch.index.analysis.AnalyzerScope) MapperRegistry(org.opensearch.indices.mapper.MapperRegistry) Directory(org.apache.lucene.store.Directory) XContentFactory(org.opensearch.common.xcontent.XContentFactory) Collections.singletonMap(java.util.Collections.singletonMap) Mockito.anyString(org.mockito.Mockito.anyString) ScriptService(org.opensearch.script.ScriptService) Collections.emptyMap(java.util.Collections.emptyMap) NamedAnalyzer(org.opensearch.index.analysis.NamedAnalyzer) ScriptPlugin(org.opensearch.plugins.ScriptPlugin) Collections.emptyList(java.util.Collections.emptyList) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Collection(java.util.Collection) Settings(org.opensearch.common.settings.Settings) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) Plugin(org.opensearch.plugins.Plugin) SearchLookup(org.opensearch.search.lookup.SearchLookup) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) Collectors.toList(java.util.stream.Collectors.toList) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) BytesArray(org.opensearch.common.bytes.BytesArray) JsonXContent(org.opensearch.common.xcontent.json.JsonXContent) IndexSettings(org.opensearch.index.IndexSettings) QueryShardContext(org.opensearch.index.query.QueryShardContext) XContentType(org.opensearch.common.xcontent.XContentType) RandomIndexWriter(org.apache.lucene.index.RandomIndexWriter) Mockito.any(org.mockito.Mockito.any) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig) Collections(java.util.Collections) IndexReader(org.apache.lucene.index.IndexReader) IndexAnalyzers(org.opensearch.index.analysis.IndexAnalyzers) Mockito.mock(org.mockito.Mockito.mock) ScriptService(org.opensearch.script.ScriptService) ScriptModule(org.opensearch.script.ScriptModule) IndicesModule(org.opensearch.indices.IndicesModule) MapperRegistry(org.opensearch.indices.mapper.MapperRegistry) MapperPlugin(org.opensearch.plugins.MapperPlugin) IndexSettings(org.opensearch.index.IndexSettings) SimilarityService(org.opensearch.index.similarity.SimilarityService) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ScriptPlugin(org.opensearch.plugins.ScriptPlugin)

Aggregations

MapperRegistry (org.opensearch.indices.mapper.MapperRegistry)8 Settings (org.opensearch.common.settings.Settings)5 Collections (java.util.Collections)4 Map (java.util.Map)4 Version (org.opensearch.Version)4 IndexSettings (org.opensearch.index.IndexSettings)4 IndexAnalyzers (org.opensearch.index.analysis.IndexAnalyzers)4 SimilarityService (org.opensearch.index.similarity.SimilarityService)4 Set (java.util.Set)3 Matchers.containsString (org.hamcrest.Matchers.containsString)3 MapperService (org.opensearch.index.mapper.MapperService)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 Collections.emptyMap (java.util.Collections.emptyMap)2 Collections.singletonMap (java.util.Collections.singletonMap)2 Iterator (java.util.Iterator)2 List (java.util.List)2 Function (java.util.function.Function)2 Predicate (java.util.function.Predicate)2