summaryrefslogtreecommitdiff
path: root/core/src/test/java/org/elasticsearch/bwcompat/BasicBackwardsCompatibilityIT.java
blob: 43633fe6f275039e323e5368dba7f578f8d036b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.elasticsearch.bwcompat;

import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import org.apache.lucene.index.Fields;
import org.apache.lucene.util.English;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.Version;
import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.analyze.AnalyzeResponse;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.explain.ExplainResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetRequest;
import org.elasticsearch.action.get.MultiGetRequestBuilder;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.termvectors.TermVectorsResponse;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.internal.FieldNamesFieldMapper;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.test.ESBackcompatTestCase;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery;
import static org.elasticsearch.index.query.QueryBuilders.existsQuery;
import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.notNullValue;

/**
 */
public class BasicBackwardsCompatibilityIT extends ESBackcompatTestCase {

    /**
     * Basic test using Index & Realtime Get with external versioning. This test ensures routing works correctly across versions.
     */
    public void testExternalVersion() throws Exception {
        createIndex("test");
        final boolean routing = randomBoolean();
        int numDocs = randomIntBetween(10, 20);
        for (int i = 0; i < numDocs; i++) {
            String id = Integer.toString(i);
            String routingKey = routing ? randomRealisticUnicodeOfLength(10) : null;
            final long version = randomIntBetween(0, Integer.MAX_VALUE);
            client().prepareIndex("test", "type1", id).setRouting(routingKey).setVersion(version).setVersionType(VersionType.EXTERNAL).setSource("field1", English.intToEnglish(i)).get();
            GetResponse get = client().prepareGet("test", "type1", id).setRouting(routingKey).setVersion(version).get();
            assertThat("Document with ID " + id + " should exist but doesn't", get.isExists(), is(true));
            assertThat(get.getVersion(), equalTo(version));
            final long nextVersion = version + randomIntBetween(0, Integer.MAX_VALUE);
            client().prepareIndex("test", "type1", id).setRouting(routingKey).setVersion(nextVersion).setVersionType(VersionType.EXTERNAL).setSource("field1", English.intToEnglish(i)).get();
            get = client().prepareGet("test", "type1", id).setRouting(routingKey).setVersion(nextVersion).get();
            assertThat("Document with ID " + id + " should exist but doesn't", get.isExists(), is(true));
            assertThat(get.getVersion(), equalTo(nextVersion));
        }
    }

    /**
     * Basic test using Index &amp; Realtime Get with internal versioning. This test ensures routing works correctly across versions.
     */
    public void testInternalVersion() throws Exception {
        createIndex("test");
        final boolean routing = randomBoolean();
        int numDocs = randomIntBetween(10, 20);
        for (int i = 0; i < numDocs; i++) {
            String routingKey = routing ? randomRealisticUnicodeOfLength(10) : null;
            String id = Integer.toString(i);
            assertThat(id, client().prepareIndex("test", "type1", id).setRouting(routingKey).setSource("field1", English.intToEnglish(i)).get().isCreated(), is(true));
            GetResponse get = client().prepareGet("test", "type1", id).setRouting(routingKey).setVersion(1).get();
            assertThat("Document with ID " + id + " should exist but doesn't", get.isExists(), is(true));
            assertThat(get.getVersion(), equalTo(1l));
            client().prepareIndex("test", "type1", id).setRouting(routingKey).setSource("field1", English.intToEnglish(i)).execute().actionGet();
            get = client().prepareGet("test", "type1", id).setRouting(routingKey).setVersion(2).get();
            assertThat("Document with ID " + id + " should exist but doesn't", get.isExists(), is(true));
            assertThat(get.getVersion(), equalTo(2l));
        }

        assertVersionCreated(compatibilityVersion(), "test");
    }

    /**
     * Very basic bw compat test with a mixed version cluster random indexing and lookup by ID via term query
     */
    public void testIndexAndSearch() throws Exception {
        createIndex("test");
        int numDocs = randomIntBetween(10, 20);
        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);
        }
        assertVersionCreated(compatibilityVersion(), "test");
    }

    public void testRecoverFromPreviousVersion() throws ExecutionException, InterruptedException {
        if (backwardsCluster().numNewDataNodes() == 0) {
            backwardsCluster().startNewNode();
        }
        assertAcked(prepareCreate("test").setSettings(Settings.builder().put("index.routing.allocation.exclude._name", backwardsCluster().newNodePattern()).put(indexSettings())));
        ensureYellow();
        assertAllShardsOnNodes("test", backwardsCluster().backwardsNodePattern());
        int numDocs = randomIntBetween(100, 150);
        ArrayList<String> ids = new ArrayList<>();
        logger.info(" --> indexing [{}] docs", numDocs);
        IndexRequestBuilder[] docs = new IndexRequestBuilder[numDocs];
        for (int i = 0; i < numDocs; i++) {
            String id = randomRealisticUnicodeOfLength(10) + String.valueOf(i);
            ids.add(id);
            docs[i] = client().prepareIndex("test", "type1", id).setSource("field1", English.intToEnglish(i));
        }
        indexRandom(true, docs);
        SearchResponse countResponse = client().prepareSearch().setSize(0).get();
        assertHitCount(countResponse, numDocs);

        if (randomBoolean()) {
            logger.info(" --> moving index to new nodes");
            backwardsCluster().allowOnlyNewNodes("test");
        } else {
            logger.info(" --> allow index to on all nodes");
            backwardsCluster().allowOnAllNodes("test");
        }

        logger.info(" --> indexing [{}] more docs", numDocs);
        // sometimes index while relocating
        if (randomBoolean()) {
            for (int i = 0; i < numDocs; i++) {
                String id = randomRealisticUnicodeOfLength(10) + String.valueOf(numDocs + i);
                ids.add(id);
                docs[i] = client().prepareIndex("test", "type1", id).setSource("field1", English.intToEnglish(numDocs + i));
            }
            indexRandom(true, docs);
            if (compatibilityVersion().before(Version.V_1_3_0)) {
                // issue another refresh through a new node to side step issue #6545
                assertNoFailures(backwardsCluster().internalCluster().dataNodeClient().admin().indices().prepareRefresh().setIndicesOptions(IndicesOptions.lenientExpandOpen()).execute().get());
            }
            numDocs *= 2;
        }

        logger.info(" --> waiting for relocation to complete", numDocs);
        ensureYellow("test");// move all shards to the new node (it waits on relocation)
        final int numIters = randomIntBetween(10, 20);
        for (int i = 0; i < numIters; i++) {
            assertSearchHits(client().prepareSearch().setSize(ids.size()).get(), ids.toArray(new String[ids.size()]));
        }
        assertVersionCreated(compatibilityVersion(), "test");
    }

    /**
     * Test that ensures that we will never recover from a newer to an older version (we are not forward compatible)
     */
    public void testNoRecoveryFromNewNodes() throws ExecutionException, InterruptedException {
        assertAcked(prepareCreate("test").setSettings(Settings.builder().put("index.routing.allocation.exclude._name", backwardsCluster().backwardsNodePattern()).put(indexSettings())));
        if (backwardsCluster().numNewDataNodes() == 0) {
            backwardsCluster().startNewNode();
        }
        ensureYellow();
        assertAllShardsOnNodes("test", backwardsCluster().newNodePattern());
        if (randomBoolean()) {
            backwardsCluster().allowOnAllNodes("test");
        }
        int numDocs = randomIntBetween(100, 150);
        IndexRequestBuilder[] docs = new IndexRequestBuilder[numDocs];
        for (int i = 0; i < numDocs; i++) {
            docs[i] = client().prepareIndex("test", "type1", randomRealisticUnicodeOfLength(10) + String.valueOf(i)).setSource("field1", English.intToEnglish(i), "num_int", randomInt(), "num_double", randomDouble());
        }
        indexRandom(true, docs);
        backwardsCluster().allowOnAllNodes("test");
        while (ensureYellow() != ClusterHealthStatus.GREEN) {
            backwardsCluster().startNewNode();
        }
        assertAllShardsOnNodes("test", backwardsCluster().newNodePattern());
        SearchResponse countResponse = client().prepareSearch().setSize(0).get();
        assertHitCount(countResponse, numDocs);
        final int numIters = randomIntBetween(10, 20);
        for (int i = 0; i < numIters; i++) {
            countResponse = client().prepareSearch().setSize(0).get();
            assertHitCount(countResponse, numDocs);
            assertSimpleSort("num_double", "num_int");
        }
        assertVersionCreated(compatibilityVersion(), "test");
    }


    public void assertSimpleSort(String... numericFields) {
        for (String field : numericFields) {
            SearchResponse searchResponse = client().prepareSearch().addSort(field, SortOrder.ASC).get();
            SearchHit[] hits = searchResponse.getHits().getHits();
            assertThat(hits.length, greaterThan(0));
            Number previous = null;
            for (SearchHit hit : hits) {
                assertNotNull(hit.getSource().get(field));
                if (previous != null) {
                    assertThat(previous.doubleValue(), lessThanOrEqualTo(((Number) hit.getSource().get(field)).doubleValue()));
                }
                previous = (Number) hit.getSource().get(field);
            }
        }
    }

    @Override
    public void assertAllShardsOnNodes(String index, String pattern) {
        ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
        for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) {
            for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
                for (ShardRouting shardRouting : indexShardRoutingTable) {
                    if (shardRouting.currentNodeId() != null && index.equals(shardRouting.getIndex())) {
                        String name = clusterState.nodes().get(shardRouting.currentNodeId()).name();
                        assertThat("Allocated on new node: " + name, Regex.simpleMatch(pattern, name), is(true));
                    }
                }
            }
        }
    }

    /**
     * Upgrades a single node to the current version
     */
    public void testIndexUpgradeSingleNode() throws Exception {
        assertAcked(prepareCreate("test").setSettings(Settings.builder().put("index.routing.allocation.exclude._name", backwardsCluster().newNodePattern()).put(indexSettings())));
        ensureYellow();
        int numDocs = randomIntBetween(100, 150);
        IndexRequestBuilder[] docs = new IndexRequestBuilder[numDocs];
        for (int i = 0; i < numDocs; i++) {
            docs[i] = client().prepareIndex("test", "type1", String.valueOf(i)).setSource("field1", English.intToEnglish(i), "num_int", randomInt(), "num_double", randomDouble());
        }

        indexRandom(true, docs);
        assertAllShardsOnNodes("test", backwardsCluster().backwardsNodePattern());
        disableAllocation("test");
        backwardsCluster().allowOnAllNodes("test");
        SearchResponse countResponse = client().prepareSearch().setSize(0).get();
        assertHitCount(countResponse, numDocs);
        backwardsCluster().upgradeOneNode();
        ensureYellow();
        if (randomBoolean()) {
            for (int i = 0; i < numDocs; i++) {
                docs[i] = client().prepareIndex("test", "type1", String.valueOf(i)).setSource("field1", English.intToEnglish(i), "num_int", randomInt(), "num_double", randomDouble());
            }
            indexRandom(true, docs);
        }
        enableAllocation("test");
        ensureYellow();
        final int numIters = randomIntBetween(1, 20);
        for (int i = 0; i < numIters; i++) {
            assertHitCount(client().prepareSearch().setSize(0).get(), numDocs);
            assertSimpleSort("num_double", "num_int");
        }
        assertVersionCreated(compatibilityVersion(), "test");
    }

    /**
     * Test that allocates an index on one or more old nodes and then do a rolling upgrade
     * one node after another is shut down and restarted from a newer version and we verify
     * that all documents are still around after each nodes upgrade.
     */
    public void testIndexRollingUpgrade() throws Exception {
        String[] indices = new String[randomIntBetween(1, 3)];
        for (int i = 0; i < indices.length; i++) {
            indices[i] = "test" + i;
            assertAcked(prepareCreate(indices[i]).setSettings(Settings.builder().put("index.routing.allocation.exclude._name", backwardsCluster().newNodePattern()).put(indexSettings())));
        }

        int numDocs = randomIntBetween(100, 150);
        IndexRequestBuilder[] docs = new IndexRequestBuilder[numDocs];
        String[] indexForDoc = new String[docs.length];
        for (int i = 0; i < numDocs; i++) {
            docs[i] = client().prepareIndex(indexForDoc[i] = RandomPicks.randomFrom(getRandom(), indices), "type1", String.valueOf(i)).setSource("field1", English.intToEnglish(i), "num_int", randomInt(), "num_double", randomDouble());
        }
        indexRandom(true, docs);
        for (String index : indices) {
            assertAllShardsOnNodes(index, backwardsCluster().backwardsNodePattern());
        }
        disableAllocation(indices);
        backwardsCluster().allowOnAllNodes(indices);
        logClusterState();
        boolean upgraded;
        do {
            logClusterState();
            SearchResponse countResponse = client().prepareSearch().setSize(0).get();
            assertHitCount(countResponse, numDocs);
            assertSimpleSort("num_double", "num_int");
            upgraded = backwardsCluster().upgradeOneNode();
            ensureYellow();
            countResponse = client().prepareSearch().setSize(0).get();
            assertHitCount(countResponse, numDocs);
            for (int i = 0; i < numDocs; i++) {
                docs[i] = client().prepareIndex(indexForDoc[i], "type1", String.valueOf(i)).setSource("field1", English.intToEnglish(i), "num_int", randomInt(), "num_double", randomDouble());
            }
            indexRandom(true, docs);
        } while (upgraded);
        enableAllocation(indices);
        ensureYellow();
        SearchResponse countResponse = client().prepareSearch().setSize(0).get();
        assertHitCount(countResponse, numDocs);
        assertSimpleSort("num_double", "num_int");

        String[] newIndices = new String[randomIntBetween(1, 3)];

        for (int i = 0; i < newIndices.length; i++) {
            newIndices[i] = "new_index" + i;
            createIndex(newIndices[i]);
        }
        assertVersionCreated(Version.CURRENT, newIndices); // new indices are all created with the new version
        assertVersionCreated(compatibilityVersion(), indices);
    }

    public void assertVersionCreated(Version version, String... indices) {
        GetSettingsResponse getSettingsResponse = client().admin().indices().prepareGetSettings(indices).get();
        ImmutableOpenMap<String, Settings> indexToSettings = getSettingsResponse.getIndexToSettings();
        for (String index : indices) {
            Settings settings = indexToSettings.get(index);
            assertThat(settings.getAsVersion(IndexMetaData.SETTING_VERSION_CREATED, null), notNullValue());
            assertThat(settings.getAsVersion(IndexMetaData.SETTING_VERSION_CREATED, null), equalTo(version));
        }
    }


    public void testUnsupportedFeatures() throws IOException {
        XContentBuilder mapping = XContentBuilder.builder(JsonXContent.jsonXContent)
                .startObject()
                    .startObject("type")
                        .startObject(FieldNamesFieldMapper.NAME)
                           // by setting randomly index to no we also test the pre-1.3 behavior
                            .field("index", randomFrom("no", "not_analyzed"))
                            .field("store", randomFrom("no", "yes"))
                        .endObject()
                    .endObject()
                .endObject();

        try {
            assertAcked(prepareCreate("test").
                    setSettings(Settings.builder().put("index.routing.allocation.exclude._name", backwardsCluster().newNodePattern()).put(indexSettings()))
                    .addMapping("type", mapping));
        } catch (MapperParsingException ex) {
            assertThat(ex.getCause(), instanceOf(IllegalArgumentException.class));
            assertThat(ExceptionsHelper.detailedMessage(ex).contains("type=_field_names is not supported on indices created before version 1.3.0"), equalTo(true));
        }

    }

    /**
     * This filter had a major upgrade in 1.3 where we started to index the field names. Lets see if they still work as expected...
     * this test is basically copied from SimpleQueryTests...
     */
    public void testExistsFilter() throws IOException, ExecutionException, InterruptedException {
        int indexId = 0;
        String indexName;

        for (; ; ) {
            indexName = "test_"+indexId++;
            createIndex(indexName);
            ensureYellow();
            indexRandom(true,
                    client().prepareIndex(indexName, "type1", "1").setSource(jsonBuilder().startObject().startObject("obj1").field("obj1_val", "1").endObject().field("x1", "x_1").field("field1", "value1_1").field("field2", "value2_1").endObject()),
                    client().prepareIndex(indexName, "type1", "2").setSource(jsonBuilder().startObject().startObject("obj1").field("obj1_val", "1").endObject().field("x2", "x_2").field("field1", "value1_2").endObject()),
                    client().prepareIndex(indexName, "type1", "3").setSource(jsonBuilder().startObject().startObject("obj2").field("obj2_val", "1").endObject().field("y1", "y_1").field("field2", "value2_3").endObject()),
                    client().prepareIndex(indexName, "type1", "4").setSource(jsonBuilder().startObject().startObject("obj2").field("obj2_val", "1").endObject().field("y2", "y_2").field("field3", "value3_4").endObject()));

            SearchResponse countResponse = client().prepareSearch().setSize(0).setQuery(existsQuery("field1")).get();
            assertHitCount(countResponse, 2l);

            countResponse = client().prepareSearch().setSize(0).setQuery(constantScoreQuery(existsQuery("field1"))).get();
            assertHitCount(countResponse, 2l);

            countResponse = client().prepareSearch().setSize(0).setQuery(queryStringQuery("_exists_:field1")).get();
            assertHitCount(countResponse, 2l);

            countResponse = client().prepareSearch().setSize(0).setQuery(existsQuery("field2")).get();
            assertHitCount(countResponse, 2l);

            countResponse = client().prepareSearch().setSize(0).setQuery(existsQuery("field3")).get();
            assertHitCount(countResponse, 1l);

            // wildcard check
            countResponse = client().prepareSearch().setSize(0).setQuery(existsQuery("x*")).get();
            assertHitCount(countResponse, 2l);

            // object check
            countResponse = client().prepareSearch().setSize(0).setQuery(existsQuery("obj1")).get();
            assertHitCount(countResponse, 2l);

            countResponse = client().prepareSearch().setSize(0).setQuery(queryStringQuery("_missing_:field1")).get();
            assertHitCount(countResponse, 2l);

            if (!backwardsCluster().upgradeOneNode()) {
                break;
            }
            ensureYellow();
            assertVersionCreated(compatibilityVersion(), indexName); // we had an old node in the cluster so we have to be on the compat version
            assertAcked(client().admin().indices().prepareDelete(indexName));
        }

        assertVersionCreated(Version.CURRENT, indexName); // after upgrade we have current version
    }


    public Version getMasterVersion() {
        return client().admin().cluster().prepareState().get().getState().nodes().masterNode().getVersion();
    }

    public void testDeleteRoutingRequired() throws ExecutionException, InterruptedException, IOException {
        createIndexWithAlias();
        assertAcked(client().admin().indices().preparePutMapping("test").setType("test").setSource(
                XContentFactory.jsonBuilder().startObject().startObject("test").startObject("_routing").field("required", true).endObject().endObject().endObject()));
        ensureYellow("test");

        int numDocs = iterations(10, 50);
        IndexRequestBuilder[] indexRequestBuilders = new IndexRequestBuilder[numDocs];
        for (int i = 0; i < numDocs - 2; i++) {
            indexRequestBuilders[i] = client().prepareIndex("test", "test", Integer.toString(i))
                    .setRouting(randomAsciiOfLength(randomIntBetween(1, 10))).setSource("field", "value");
        }
        String firstDocId = Integer.toString(numDocs - 2);
        indexRequestBuilders[numDocs - 2] = client().prepareIndex("test", "test", firstDocId)
                .setRouting("routing").setSource("field", "value");
        String secondDocId = Integer.toString(numDocs - 1);
        String secondRouting = randomAsciiOfLength(randomIntBetween(1, 10));
        indexRequestBuilders[numDocs - 1] = client().prepareIndex("test", "test", secondDocId)
                .setRouting(secondRouting).setSource("field", "value");

        indexRandom(true, indexRequestBuilders);

        SearchResponse searchResponse = client().prepareSearch("test").get();
        assertNoFailures(searchResponse);
        assertThat(searchResponse.getHits().totalHits(), equalTo((long) numDocs));

        DeleteResponse deleteResponse = client().prepareDelete("test", "test", firstDocId).setRouting("routing").get();
        assertThat(deleteResponse.isFound(), equalTo(true));
        GetResponse getResponse = client().prepareGet("test", "test", firstDocId).setRouting("routing").get();
        assertThat(getResponse.isExists(), equalTo(false));
        refresh();
        searchResponse = client().prepareSearch("test").get();
        assertNoFailures(searchResponse);
        assertThat(searchResponse.getHits().totalHits(), equalTo((long) numDocs - 1));
    }

    public void testIndexGetAndDelete() throws ExecutionException, InterruptedException {
        createIndexWithAlias();
        ensureYellow("test");

        int numDocs = iterations(10, 50);
        for (int i = 0; i < numDocs; i++) {
            IndexResponse indexResponse = client().prepareIndex(indexOrAlias(), "type", Integer.toString(i)).setSource("field", "value-" + i).get();
            assertThat(indexResponse.isCreated(), equalTo(true));
            assertThat(indexResponse.getIndex(), equalTo("test"));
            assertThat(indexResponse.getType(), equalTo("type"));
            assertThat(indexResponse.getId(), equalTo(Integer.toString(i)));
        }
        refresh();

        String docId = Integer.toString(randomIntBetween(0, numDocs - 1));
        GetResponse getResponse = client().prepareGet(indexOrAlias(), "type", docId).get();
        assertThat(getResponse.isExists(), equalTo(true));
        assertThat(getResponse.getIndex(), equalTo("test"));
        assertThat(getResponse.getType(), equalTo("type"));
        assertThat(getResponse.getId(), equalTo(docId));

        DeleteResponse deleteResponse = client().prepareDelete(indexOrAlias(), "type", docId).get();
        assertThat(deleteResponse.isFound(), equalTo(true));
        assertThat(deleteResponse.getIndex(), equalTo("test"));
        assertThat(deleteResponse.getType(), equalTo("type"));
        assertThat(deleteResponse.getId(), equalTo(docId));

        getResponse = client().prepareGet(indexOrAlias(), "type", docId).get();
        assertThat(getResponse.isExists(), equalTo(false));

        refresh();

        SearchResponse searchResponse = client().prepareSearch(indexOrAlias()).get();
        assertThat(searchResponse.getHits().totalHits(), equalTo((long) numDocs - 1));
    }

    public void testUpdate() {
        createIndexWithAlias();
        ensureYellow("test");

        UpdateRequestBuilder updateRequestBuilder = client().prepareUpdate(indexOrAlias(), "type1", "1")
                .setUpsert("field1", "value1").setDoc("field2", "value2");

        UpdateResponse updateResponse = updateRequestBuilder.get();
        assertThat(updateResponse.getIndex(), equalTo("test"));
        assertThat(updateResponse.getType(), equalTo("type1"));
        assertThat(updateResponse.getId(), equalTo("1"));
        assertThat(updateResponse.isCreated(), equalTo(true));

        GetResponse getResponse = client().prepareGet("test", "type1", "1").get();
        assertThat(getResponse.isExists(), equalTo(true));
        assertThat(getResponse.getSourceAsMap().containsKey("field1"), equalTo(true));
        assertThat(getResponse.getSourceAsMap().containsKey("field2"), equalTo(false));

        updateResponse = updateRequestBuilder.get();
        assertThat(updateResponse.getIndex(), equalTo("test"));
        assertThat(updateResponse.getType(), equalTo("type1"));
        assertThat(updateResponse.getId(), equalTo("1"));
        assertThat(updateResponse.isCreated(), equalTo(false));

        getResponse = client().prepareGet("test", "type1", "1").get();
        assertThat(getResponse.isExists(), equalTo(true));
        assertThat(getResponse.getSourceAsMap().containsKey("field1"), equalTo(true));
        assertThat(getResponse.getSourceAsMap().containsKey("field2"), equalTo(true));
    }

    public void testAnalyze() {
        createIndexWithAlias();
        assertAcked(client().admin().indices().preparePutMapping("test").setType("test").setSource("field", "type=string,analyzer=keyword"));
        ensureYellow("test");
        AnalyzeResponse analyzeResponse = client().admin().indices().prepareAnalyze("this is a test").setIndex(indexOrAlias()).setField("field").get();
        assertThat(analyzeResponse.getTokens().size(), equalTo(1));
        assertThat(analyzeResponse.getTokens().get(0).getTerm(), equalTo("this is a test"));
    }

    public void testExplain() {
        createIndexWithAlias();
        ensureYellow("test");

        client().prepareIndex(indexOrAlias(), "test", "1").setSource("field", "value1").get();
        refresh();

        ExplainResponse response = client().prepareExplain(indexOrAlias(), "test", "1")
                .setQuery(QueryBuilders.termQuery("field", "value1")).get();
        assertThat(response.isExists(), equalTo(true));
        assertThat(response.isMatch(), equalTo(true));
        assertThat(response.getExplanation(), notNullValue());
        assertThat(response.getExplanation().isMatch(), equalTo(true));
        assertThat(response.getExplanation().getDetails().length, equalTo(1));
    }

    public void testGetTermVector() throws IOException {
        createIndexWithAlias();
        assertAcked(client().admin().indices().preparePutMapping("test").setType("type1").setSource("field", "type=string,term_vector=with_positions_offsets_payloads").get());
        ensureYellow("test");

        client().prepareIndex(indexOrAlias(), "type1", "1")
                .setSource("field", "the quick brown fox jumps over the lazy dog").get();
        refresh();

        TermVectorsResponse termVectorsResponse = client().prepareTermVectors(indexOrAlias(), "type1", "1").get();
        assertThat(termVectorsResponse.getIndex(), equalTo("test"));
        assertThat(termVectorsResponse.isExists(), equalTo(true));
        Fields fields = termVectorsResponse.getFields();
        assertThat(fields.size(), equalTo(1));
        assertThat(fields.terms("field").size(), equalTo(8l));
    }

    public void testIndicesStats() {
        createIndex("test");
        ensureYellow("test");

        IndicesStatsResponse indicesStatsResponse = client().admin().indices().prepareStats().all().get();
        assertThat(indicesStatsResponse.getIndices().size(), equalTo(1));
        assertThat(indicesStatsResponse.getIndices().containsKey("test"), equalTo(true));
    }

    public void testMultiGet() throws ExecutionException, InterruptedException {
        createIndexWithAlias();
        ensureYellow("test");

        int numDocs = iterations(10, 50);
        IndexRequestBuilder[] indexRequestBuilders = new IndexRequestBuilder[numDocs];
        for (int i = 0; i < numDocs; i++) {
            indexRequestBuilders[i] = client().prepareIndex("test", "type", Integer.toString(i)).setSource("field", "value" + Integer.toString(i));
        }
        indexRandom(false, indexRequestBuilders);

        int iterations = iterations(1, numDocs);
        MultiGetRequestBuilder multiGetRequestBuilder = client().prepareMultiGet();
        for (int i = 0; i < iterations; i++) {
            multiGetRequestBuilder.add(new MultiGetRequest.Item(indexOrAlias(), "type", Integer.toString(randomInt(numDocs - 1))));
        }
        MultiGetResponse multiGetResponse = multiGetRequestBuilder.get();
        assertThat(multiGetResponse.getResponses().length, equalTo(iterations));
        for (int i = 0; i < multiGetResponse.getResponses().length; i++) {
            MultiGetItemResponse multiGetItemResponse = multiGetResponse.getResponses()[i];
            assertThat(multiGetItemResponse.isFailed(), equalTo(false));
            assertThat(multiGetItemResponse.getIndex(), equalTo("test"));
            assertThat(multiGetItemResponse.getType(), equalTo("type"));
            assertThat(multiGetItemResponse.getId(), equalTo(multiGetRequestBuilder.request().getItems().get(i).id()));
            assertThat(multiGetItemResponse.getResponse().isExists(), equalTo(true));
            assertThat(multiGetItemResponse.getResponse().getIndex(), equalTo("test"));
            assertThat(multiGetItemResponse.getResponse().getType(), equalTo("type"));
            assertThat(multiGetItemResponse.getResponse().getId(), equalTo(multiGetRequestBuilder.request().getItems().get(i).id()));
        }

    }

    public void testScroll() throws ExecutionException, InterruptedException {
        createIndex("test");
        ensureYellow("test");

        int numDocs = iterations(10, 100);
        IndexRequestBuilder[] indexRequestBuilders = new IndexRequestBuilder[numDocs];
        for (int i = 0; i < numDocs; i++) {
            indexRequestBuilders[i] = client().prepareIndex("test", "type", Integer.toString(i)).setSource("field", "value" + Integer.toString(i));
        }
        indexRandom(true, indexRequestBuilders);

        int size = randomIntBetween(1, 10);
        SearchRequestBuilder searchRequestBuilder = client().prepareSearch("test").setScroll("1m").setSize(size);

        SearchResponse searchResponse = searchRequestBuilder.get();
        assertThat(searchResponse.getScrollId(), notNullValue());
        assertHitCount(searchResponse, numDocs);
        int hits = 0;
        assertThat(searchResponse.getHits().getHits().length, greaterThan(0));
        hits += searchResponse.getHits().getHits().length;

        try {
            do {
                searchResponse = client().prepareSearchScroll(searchResponse.getScrollId()).setScroll("1m").get();
                assertThat(searchResponse.getScrollId(), notNullValue());
                assertHitCount(searchResponse, numDocs);
                hits += searchResponse.getHits().getHits().length;
            } while (searchResponse.getHits().getHits().length > 0);
            assertThat(hits, equalTo(numDocs));
        } finally {
            clearScroll(searchResponse.getScrollId());
        }
    }

    private static String indexOrAlias() {
        return randomBoolean() ? "test" : "alias";
    }

    private void createIndexWithAlias() {
        assertAcked(prepareCreate("test").addAlias(new Alias("alias")));
    }
}