Search in sources :

Example 6 with IndexRequestBuilder

use of org.elasticsearch.action.index.IndexRequestBuilder in project elasticsearch by elastic.

the class CircuitBreakerServiceIT method testMemoryBreaker.

public void testMemoryBreaker() throws Exception {
    if (noopBreakerUsed()) {
        logger.info("--> noop breakers used, skipping test");
        return;
    }
    assertAcked(prepareCreate("cb-test", 1, Settings.builder().put(SETTING_NUMBER_OF_REPLICAS, between(0, 1))).addMapping("type", "test", "type=text,fielddata=true"));
    final Client client = client();
    // index some different terms so we have some field data for loading
    int docCount = scaledRandomIntBetween(300, 1000);
    List<IndexRequestBuilder> reqs = new ArrayList<>();
    for (long id = 0; id < docCount; id++) {
        reqs.add(client.prepareIndex("cb-test", "type", Long.toString(id)).setSource("test", "value" + id));
    }
    indexRandom(true, false, true, reqs);
    // clear field data cache (thus setting the loaded field data back to 0)
    clearFieldData();
    // Update circuit breaker settings
    Settings settings = Settings.builder().put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING.getKey(), "100b").put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_OVERHEAD_SETTING.getKey(), 1.05).build();
    assertAcked(client.admin().cluster().prepareUpdateSettings().setTransientSettings(settings));
    // execute a search that loads field data (sorting on the "test" field)
    // again, this time it should trip the breaker
    SearchRequestBuilder searchRequest = client.prepareSearch("cb-test").setQuery(matchAllQuery()).addSort("test", SortOrder.DESC);
    String errMsg = "Data too large, data for [test] would be";
    assertFailures(searchRequest, RestStatus.INTERNAL_SERVER_ERROR, containsString(errMsg));
    errMsg = "which is larger than the limit of [100/100b]";
    assertFailures(searchRequest, RestStatus.INTERNAL_SERVER_ERROR, containsString(errMsg));
    NodesStatsResponse stats = client.admin().cluster().prepareNodesStats().setBreaker(true).get();
    int breaks = 0;
    for (NodeStats stat : stats.getNodes()) {
        CircuitBreakerStats breakerStats = stat.getBreaker().getStats(CircuitBreaker.FIELDDATA);
        breaks += breakerStats.getTrippedCount();
    }
    assertThat(breaks, greaterThanOrEqualTo(1));
}
Also used : IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) NodesStatsResponse(org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse) NodeStats(org.elasticsearch.action.admin.cluster.node.stats.NodeStats) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) CircuitBreakerStats(org.elasticsearch.indices.breaker.CircuitBreakerStats) ArrayList(java.util.ArrayList) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Client(org.elasticsearch.client.Client) Settings(org.elasticsearch.common.settings.Settings) BreakerSettings(org.elasticsearch.indices.breaker.BreakerSettings)

Example 7 with IndexRequestBuilder

use of org.elasticsearch.action.index.IndexRequestBuilder in project elasticsearch by elastic.

the class OpenCloseIndexIT method testOpenCloseWithDocs.

public void testOpenCloseWithDocs() throws IOException, ExecutionException, InterruptedException {
    String mapping = XContentFactory.jsonBuilder().startObject().startObject("type").startObject("properties").startObject("test").field("type", "keyword").endObject().endObject().endObject().endObject().string();
    assertAcked(client().admin().indices().prepareCreate("test").addMapping("type", mapping, XContentType.JSON));
    ensureGreen();
    int docs = between(10, 100);
    IndexRequestBuilder[] builder = new IndexRequestBuilder[docs];
    for (int i = 0; i < docs; i++) {
        builder[i] = client().prepareIndex("test", "type", "" + i).setSource("test", "init");
    }
    indexRandom(true, builder);
    if (randomBoolean()) {
        client().admin().indices().prepareFlush("test").setForce(true).execute().get();
    }
    client().admin().indices().prepareClose("test").execute().get();
    // check the index still contains the records that we indexed
    client().admin().indices().prepareOpen("test").execute().get();
    ensureGreen();
    SearchResponse searchResponse = client().prepareSearch().setTypes("type").setQuery(QueryBuilders.matchQuery("test", "init")).get();
    assertNoFailures(searchResponse);
    assertHitCount(searchResponse, docs);
}
Also used : IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) Matchers.containsString(org.hamcrest.Matchers.containsString) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 8 with IndexRequestBuilder

use of org.elasticsearch.action.index.IndexRequestBuilder in project elasticsearch by elastic.

the class TruncatedRecoveryIT method testCancelRecoveryAndResume.

/**
     * This test tries to truncate some of larger files in the index to trigger leftovers on the recovery
     * target. This happens during recovery when the last chunk of the file is transferred to the replica
     * we just throw an exception to make sure the recovery fails and we leave some half baked files on the target.
     * Later we allow full recovery to ensure we can still recover and don't run into corruptions.
     */
public void testCancelRecoveryAndResume() throws Exception {
    assertTrue(client().admin().cluster().prepareUpdateSettings().setTransientSettings(Settings.builder().put(CHUNK_SIZE_SETTING.getKey(), new ByteSizeValue(randomIntBetween(50, 300), ByteSizeUnit.BYTES))).get().isAcknowledged());
    NodesStatsResponse nodeStats = client().admin().cluster().prepareNodesStats().get();
    List<NodeStats> dataNodeStats = new ArrayList<>();
    for (NodeStats stat : nodeStats.getNodes()) {
        if (stat.getNode().isDataNode()) {
            dataNodeStats.add(stat);
        }
    }
    assertThat(dataNodeStats.size(), greaterThanOrEqualTo(2));
    Collections.shuffle(dataNodeStats, random());
    // we use 2 nodes a lucky and unlucky one
    // the lucky one holds the primary
    // the unlucky one gets the replica and the truncated leftovers
    NodeStats primariesNode = dataNodeStats.get(0);
    NodeStats unluckyNode = dataNodeStats.get(1);
    // create the index and prevent allocation on any other nodes than the lucky one
    // we have no replicas so far and make sure that we allocate the primary on the lucky node
    assertAcked(prepareCreate("test").addMapping("type1", "field1", "type=text", "the_id", "type=text").setSettings(Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0).put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, numberOfShards()).put("index.routing.allocation.include._name", // only allocate on the lucky node
    primariesNode.getNode().getName())));
    // index some docs and check if they are coming back
    int numDocs = randomIntBetween(100, 200);
    List<IndexRequestBuilder> builder = new ArrayList<>();
    for (int i = 0; i < numDocs; i++) {
        String id = Integer.toString(i);
        builder.add(client().prepareIndex("test", "type1", id).setSource("field1", English.intToEnglish(i), "the_id", id));
    }
    indexRandom(true, builder);
    for (int i = 0; i < numDocs; i++) {
        String id = Integer.toString(i);
        assertHitCount(client().prepareSearch().setQuery(QueryBuilders.termQuery("the_id", id)).get(), 1);
    }
    ensureGreen();
    // ensure we have flushed segments and make them a big one via optimize
    client().admin().indices().prepareFlush().setForce(true).get();
    client().admin().indices().prepareForceMerge().setMaxNumSegments(1).setFlush(true).get();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean truncate = new AtomicBoolean(true);
    for (NodeStats dataNode : dataNodeStats) {
        MockTransportService mockTransportService = ((MockTransportService) internalCluster().getInstance(TransportService.class, dataNode.getNode().getName()));
        mockTransportService.addDelegate(internalCluster().getInstance(TransportService.class, unluckyNode.getNode().getName()), new MockTransportService.DelegateTransport(mockTransportService.original()) {

            @Override
            protected void sendRequest(Connection connection, long requestId, String action, TransportRequest request, TransportRequestOptions options) throws IOException {
                if (action.equals(PeerRecoveryTargetService.Actions.FILE_CHUNK)) {
                    RecoveryFileChunkRequest req = (RecoveryFileChunkRequest) request;
                    logger.debug("file chunk [{}] lastChunk: {}", req, req.lastChunk());
                    if ((req.name().endsWith("cfs") || req.name().endsWith("fdt")) && req.lastChunk() && truncate.get()) {
                        latch.countDown();
                        throw new RuntimeException("Caused some truncated files for fun and profit");
                    }
                }
                super.sendRequest(connection, requestId, action, request, options);
            }
        });
    }
    //
    logger.info("--> bumping replicas to 1");
    client().admin().indices().prepareUpdateSettings("test").setSettings(Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1).put(// now allow allocation on all nodes
    "index.routing.allocation.include._name", primariesNode.getNode().getName() + "," + unluckyNode.getNode().getName())).get();
    latch.await();
    // at this point we got some truncated left overs on the replica on the unlucky node
    // now we are allowing the recovery to allocate again and finish to see if we wipe the truncated files
    truncate.compareAndSet(true, false);
    ensureGreen("test");
    for (int i = 0; i < numDocs; i++) {
        String id = Integer.toString(i);
        assertHitCount(client().prepareSearch().setQuery(QueryBuilders.termQuery("the_id", id)).get(), 1);
    }
}
Also used : TransportRequest(org.elasticsearch.transport.TransportRequest) MockTransportService(org.elasticsearch.test.transport.MockTransportService) RecoveryFileChunkRequest(org.elasticsearch.indices.recovery.RecoveryFileChunkRequest) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) NodesStatsResponse(org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse) IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) NodeStats(org.elasticsearch.action.admin.cluster.node.stats.NodeStats) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MockTransportService(org.elasticsearch.test.transport.MockTransportService) TransportService(org.elasticsearch.transport.TransportService) TransportRequestOptions(org.elasticsearch.transport.TransportRequestOptions)

Example 9 with IndexRequestBuilder

use of org.elasticsearch.action.index.IndexRequestBuilder in project elasticsearch by elastic.

the class SimpleBlocksIT method canIndexDocument.

private void canIndexDocument(String index) {
    try {
        IndexRequestBuilder builder = client().prepareIndex(index, "zzz");
        builder.setSource("foo", "bar");
        IndexResponse r = builder.execute().actionGet();
        assertThat(r, notNullValue());
    } catch (ClusterBlockException e) {
        fail();
    }
}
Also used : IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) IndexResponse(org.elasticsearch.action.index.IndexResponse) CreateIndexResponse(org.elasticsearch.action.admin.indices.create.CreateIndexResponse) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException)

Example 10 with IndexRequestBuilder

use of org.elasticsearch.action.index.IndexRequestBuilder in project elasticsearch by elastic.

the class SimpleBlocksIT method canNotIndexDocument.

private void canNotIndexDocument(String index) {
    try {
        IndexRequestBuilder builder = client().prepareIndex(index, "zzz");
        builder.setSource("foo", "bar");
        builder.execute().actionGet();
        fail();
    } catch (ClusterBlockException e) {
    // all is well
    }
}
Also used : IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException)

Aggregations

IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)227 ArrayList (java.util.ArrayList)134 SearchResponse (org.elasticsearch.action.search.SearchResponse)125 ElasticsearchAssertions.assertSearchResponse (org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)48 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)45 Matchers.containsString (org.hamcrest.Matchers.containsString)38 GeoPoint (org.elasticsearch.common.geo.GeoPoint)36 CreateIndexRequestBuilder (org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder)31 CompletionSuggestionBuilder (org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder)23 Settings (org.elasticsearch.common.settings.Settings)21 IOException (java.io.IOException)19 BulkRequestBuilder (org.elasticsearch.action.bulk.BulkRequestBuilder)19 Client (org.elasticsearch.client.Client)18 SearchHit (org.elasticsearch.search.SearchHit)17 LinkedHashMap (java.util.LinkedHashMap)16 SearchHits (org.elasticsearch.search.SearchHits)16 QueryBuilder (org.elasticsearch.index.query.QueryBuilder)15 CompletionMappingBuilder (org.elasticsearch.search.suggest.CompletionSuggestSearchIT.CompletionMappingBuilder)15 CategoryContextMapping (org.elasticsearch.search.suggest.completion.context.CategoryContextMapping)15 ContextMapping (org.elasticsearch.search.suggest.completion.context.ContextMapping)15