Search in sources :

Example 26 with IndexSettings

use of org.elasticsearch.index.IndexSettings in project elasticsearch by elastic.

the class SimpleQueryParserTests method testQuoteFieldSuffix.

public void testQuoteFieldSuffix() {
    SimpleQueryParser.Settings sqpSettings = new SimpleQueryParser.Settings();
    sqpSettings.quoteFieldSuffix(".quote");
    Settings indexSettings = Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0).put(IndexMetaData.SETTING_INDEX_UUID, "some_uuid").put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build();
    IndexMetaData indexState = IndexMetaData.builder("index").settings(indexSettings).build();
    IndexSettings settings = new IndexSettings(indexState, Settings.EMPTY);
    QueryShardContext mockShardContext = new QueryShardContext(0, settings, null, null, null, null, null, xContentRegistry(), null, null, System::currentTimeMillis) {

        @Override
        public MappedFieldType fieldMapper(String name) {
            return new MockFieldMapper.FakeFieldType();
        }
    };
    SimpleQueryParser parser = new SimpleQueryParser(new StandardAnalyzer(), Collections.singletonMap("foo", 1f), -1, sqpSettings, mockShardContext);
    assertEquals(new TermQuery(new Term("foo", "bar")), parser.parse("bar"));
    assertEquals(new TermQuery(new Term("foo.quote", "bar")), parser.parse("\"bar\""));
    // Now check what happens if foo.quote does not exist
    mockShardContext = new QueryShardContext(0, settings, null, null, null, null, null, xContentRegistry(), null, null, System::currentTimeMillis) {

        @Override
        public MappedFieldType fieldMapper(String name) {
            if (name.equals("foo.quote")) {
                return null;
            }
            return new MockFieldMapper.FakeFieldType();
        }
    };
    parser = new SimpleQueryParser(new StandardAnalyzer(), Collections.singletonMap("foo", 1f), -1, sqpSettings, mockShardContext);
    assertEquals(new TermQuery(new Term("foo", "bar")), parser.parse("bar"));
    assertEquals(new TermQuery(new Term("foo", "bar")), parser.parse("\"bar\""));
}
Also used : SpanTermQuery(org.apache.lucene.search.spans.SpanTermQuery) TermQuery(org.apache.lucene.search.TermQuery) IndexSettings(org.elasticsearch.index.IndexSettings) MockFieldMapper(org.elasticsearch.index.mapper.MockFieldMapper) Term(org.apache.lucene.index.Term) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) MappedFieldType(org.elasticsearch.index.mapper.MappedFieldType) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings)

Example 27 with IndexSettings

use of org.elasticsearch.index.IndexSettings in project elasticsearch by elastic.

the class IndexStoreTests method doTestStoreDirectory.

private void doTestStoreDirectory(Index index, Path tempDir, String typeSettingValue, IndexModule.Type type) throws IOException {
    Settings.Builder settingsBuilder = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT);
    if (typeSettingValue != null) {
        settingsBuilder.put(IndexModule.INDEX_STORE_TYPE_SETTING.getKey(), typeSettingValue);
    }
    Settings settings = settingsBuilder.build();
    IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("foo", settings);
    FsDirectoryService service = new FsDirectoryService(indexSettings, null, new ShardPath(false, tempDir, tempDir, new ShardId(index, 0)));
    try (Directory directory = service.newFSDirectory(tempDir, NoLockFactory.INSTANCE)) {
        switch(type) {
            case NIOFS:
                assertTrue(type + " " + directory.toString(), directory instanceof NIOFSDirectory);
                break;
            case MMAPFS:
                assertTrue(type + " " + directory.toString(), directory instanceof MMapDirectory);
                break;
            case SIMPLEFS:
                assertTrue(type + " " + directory.toString(), directory instanceof SimpleFSDirectory);
                break;
            case FS:
                if (Constants.JRE_IS_64BIT && MMapDirectory.UNMAP_SUPPORTED) {
                    assertTrue(directory.toString(), directory instanceof MMapDirectory);
                } else if (Constants.WINDOWS) {
                    assertTrue(directory.toString(), directory instanceof SimpleFSDirectory);
                } else {
                    assertTrue(directory.toString(), directory instanceof NIOFSDirectory);
                }
                break;
            default:
                fail();
        }
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) NIOFSDirectory(org.apache.lucene.store.NIOFSDirectory) ShardPath(org.elasticsearch.index.shard.ShardPath) IndexSettings(org.elasticsearch.index.IndexSettings) MMapDirectory(org.apache.lucene.store.MMapDirectory) SimpleFSDirectory(org.apache.lucene.store.SimpleFSDirectory) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings) SimpleFSDirectory(org.apache.lucene.store.SimpleFSDirectory) MMapDirectory(org.apache.lucene.store.MMapDirectory) Directory(org.apache.lucene.store.Directory) NIOFSDirectory(org.apache.lucene.store.NIOFSDirectory)

Example 28 with IndexSettings

use of org.elasticsearch.index.IndexSettings in project elasticsearch by elastic.

the class CorruptedFileIT method testCorruptFileAndRecover.

/**
     * Tests that we can actually recover from a corruption on the primary given that we have replica shards around.
     */
public void testCorruptFileAndRecover() throws ExecutionException, InterruptedException, IOException {
    int numDocs = scaledRandomIntBetween(100, 1000);
    // have enough space for 3 copies
    internalCluster().ensureAtLeastNumDataNodes(3);
    if (cluster().numDataNodes() == 3) {
        logger.info("--> cluster has [3] data nodes, corrupted primary will be overwritten");
    }
    assertThat(cluster().numDataNodes(), greaterThanOrEqualTo(3));
    assertAcked(prepareCreate("test").setSettings(Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, "1").put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, "1").put(MergePolicyConfig.INDEX_MERGE_ENABLED, false).put(MockFSIndexStore.INDEX_CHECK_INDEX_ON_CLOSE_SETTING.getKey(), // no checkindex - we corrupt shards on purpose
    false).put(IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING.getKey(), // no translog based flush - it might change the .liv / segments.N files
    new ByteSizeValue(1, ByteSizeUnit.PB))));
    ensureGreen();
    disableAllocation("test");
    IndexRequestBuilder[] builders = new IndexRequestBuilder[numDocs];
    for (int i = 0; i < builders.length; i++) {
        builders[i] = client().prepareIndex("test", "type").setSource("field", "value");
    }
    indexRandom(true, builders);
    ensureGreen();
    assertAllSuccessful(client().admin().indices().prepareFlush().setForce(true).execute().actionGet());
    // we have to flush at least once here since we don't corrupt the translog
    SearchResponse countResponse = client().prepareSearch().setSize(0).get();
    assertHitCount(countResponse, numDocs);
    final int numShards = numShards("test");
    ShardRouting corruptedShardRouting = corruptRandomPrimaryFile();
    logger.info("--> {} corrupted", corruptedShardRouting);
    enableAllocation("test");
    /*
         * we corrupted the primary shard - now lets make sure we never recover from it successfully
         */
    Settings build = Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, "2").build();
    client().admin().indices().prepareUpdateSettings("test").setSettings(build).get();
    ClusterHealthResponse health = client().admin().cluster().health(Requests.clusterHealthRequest("test").waitForGreenStatus().timeout(// sometimes due to cluster rebalacing and random settings default timeout is just not enough.
    "5m").waitForNoRelocatingShards(true)).actionGet();
    if (health.isTimedOut()) {
        logger.info("cluster state:\n{}\n{}", client().admin().cluster().prepareState().get().getState(), client().admin().cluster().preparePendingClusterTasks().get());
        assertThat("timed out waiting for green state", health.isTimedOut(), equalTo(false));
    }
    assertThat(health.getStatus(), equalTo(ClusterHealthStatus.GREEN));
    final int numIterations = scaledRandomIntBetween(5, 20);
    for (int i = 0; i < numIterations; i++) {
        SearchResponse response = client().prepareSearch().setSize(numDocs).get();
        assertHitCount(response, numDocs);
    }
    /*
         * now hook into the IndicesService and register a close listener to
         * run the checkindex. if the corruption is still there we will catch it.
         */
    // primary + 2 replicas
    final CountDownLatch latch = new CountDownLatch(numShards * 3);
    final CopyOnWriteArrayList<Exception> exception = new CopyOnWriteArrayList<>();
    final IndexEventListener listener = new IndexEventListener() {

        @Override
        public void afterIndexShardClosed(ShardId sid, @Nullable IndexShard indexShard, Settings indexSettings) {
            if (indexShard != null) {
                Store store = indexShard.store();
                store.incRef();
                try {
                    if (!Lucene.indexExists(store.directory()) && indexShard.state() == IndexShardState.STARTED) {
                        return;
                    }
                    try (CheckIndex checkIndex = new CheckIndex(store.directory())) {
                        BytesStreamOutput os = new BytesStreamOutput();
                        PrintStream out = new PrintStream(os, false, StandardCharsets.UTF_8.name());
                        checkIndex.setInfoStream(out);
                        out.flush();
                        CheckIndex.Status status = checkIndex.checkIndex();
                        if (!status.clean) {
                            logger.warn("check index [failure]\n{}", os.bytes().utf8ToString());
                            throw new IOException("index check failure");
                        }
                    }
                } catch (Exception e) {
                    exception.add(e);
                } finally {
                    store.decRef();
                    latch.countDown();
                }
            }
        }
    };
    for (MockIndexEventListener.TestEventListener eventListener : internalCluster().getDataNodeInstances(MockIndexEventListener.TestEventListener.class)) {
        eventListener.setNewDelegate(listener);
    }
    try {
        client().admin().indices().prepareDelete("test").get();
        latch.await();
        assertThat(exception, empty());
    } finally {
        for (MockIndexEventListener.TestEventListener eventListener : internalCluster().getDataNodeInstances(MockIndexEventListener.TestEventListener.class)) {
            eventListener.setNewDelegate(null);
        }
    }
}
Also used : MockIndexEventListener(org.elasticsearch.test.MockIndexEventListener) PrintStream(java.io.PrintStream) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) IndexShard(org.elasticsearch.index.shard.IndexShard) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) MockFSIndexStore(org.elasticsearch.test.store.MockFSIndexStore) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) TransportException(org.elasticsearch.transport.TransportException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput) SearchResponse(org.elasticsearch.action.search.SearchResponse) IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) ShardId(org.elasticsearch.index.shard.ShardId) MockIndexEventListener(org.elasticsearch.test.MockIndexEventListener) IndexEventListener(org.elasticsearch.index.shard.IndexEventListener) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings) Nullable(org.elasticsearch.common.Nullable) CheckIndex(org.apache.lucene.index.CheckIndex) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 29 with IndexSettings

use of org.elasticsearch.index.IndexSettings in project elasticsearch by elastic.

the class SimilarityServiceTests method testOverrideDefaultSimilarity.

// Tests #16594
public void testOverrideDefaultSimilarity() {
    Settings settings = Settings.builder().put("index.similarity.default.type", "classic").build();
    IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("test", settings);
    SimilarityService service = new SimilarityService(indexSettings, Collections.emptyMap());
    assertTrue(service.getDefaultSimilarity() instanceof ClassicSimilarity);
}
Also used : ClassicSimilarity(org.apache.lucene.search.similarities.ClassicSimilarity) IndexSettings(org.elasticsearch.index.IndexSettings) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings)

Example 30 with IndexSettings

use of org.elasticsearch.index.IndexSettings in project elasticsearch by elastic.

the class SimilarityServiceTests method testOverrideBuiltInSimilarityPreV3.

// Pre v3 indices could override built-in similarities
public void testOverrideBuiltInSimilarityPreV3() {
    Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.V_2_0_0).put("index.similarity.BM25.type", "classic").build();
    IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("test", settings);
    SimilarityService service = new SimilarityService(indexSettings, Collections.emptyMap());
    assertTrue(service.getSimilarity("BM25") instanceof ClassicSimilarityProvider);
}
Also used : IndexSettings(org.elasticsearch.index.IndexSettings) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings)

Aggregations

IndexSettings (org.elasticsearch.index.IndexSettings)83 Settings (org.elasticsearch.common.settings.Settings)53 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)28 Index (org.elasticsearch.index.Index)25 ShardId (org.elasticsearch.index.shard.ShardId)13 Environment (org.elasticsearch.env.Environment)12 IOException (java.io.IOException)11 QueryShardContext (org.elasticsearch.index.query.QueryShardContext)11 Path (java.nio.file.Path)9 ShardPath (org.elasticsearch.index.shard.ShardPath)9 AnalysisModule (org.elasticsearch.indices.analysis.AnalysisModule)9 Directory (org.apache.lucene.store.Directory)8 NodeEnvironment (org.elasticsearch.env.NodeEnvironment)7 ElasticsearchException (org.elasticsearch.ElasticsearchException)6 HashMap (java.util.HashMap)5 Version (org.elasticsearch.Version)5 IndexService (org.elasticsearch.index.IndexService)5 Store (org.elasticsearch.index.store.Store)5 StringReader (java.io.StringReader)4 ArrayList (java.util.ArrayList)4