summaryrefslogtreecommitdiff
path: root/core/src/main/java/org/elasticsearch/action/index/IndexRequest.java
blob: 5057fdb829c2d4cbfbcaefabb37310dc53bb641f (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
/*
 * 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.action.index;

import org.elasticsearch.ElasticsearchGenerationException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.DocumentRequest;
import org.elasticsearch.action.RoutingMissingException;
import org.elasticsearch.action.TimestampParsingException;
import org.elasticsearch.action.support.replication.ReplicationRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.mapper.internal.TimestampFieldMapper;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Map;

import static org.elasticsearch.action.ValidateActions.addValidationError;

/**
 * Index request to index a typed JSON document into a specific index and make it searchable. Best
 * created using {@link org.elasticsearch.client.Requests#indexRequest(String)}.
 *
 * The index requires the {@link #index()}, {@link #type(String)}, {@link #id(String)} and
 * {@link #source(byte[])} to be set.
 *
 * The source (content to index) can be set in its bytes form using ({@link #source(byte[])}),
 * its string form ({@link #source(String)}) or using a {@link org.elasticsearch.common.xcontent.XContentBuilder}
 * ({@link #source(org.elasticsearch.common.xcontent.XContentBuilder)}).
 *
 * If the {@link #id(String)} is not set, it will be automatically generated.
 *
 * @see IndexResponse
 * @see org.elasticsearch.client.Requests#indexRequest(String)
 * @see org.elasticsearch.client.Client#index(IndexRequest)
 */
public class IndexRequest extends ReplicationRequest<IndexRequest> implements DocumentRequest<IndexRequest> {

    /**
     * Operation type controls if the type of the index operation.
     */
    public static enum OpType {
        /**
         * Index the source. If there an existing document with the id, it will
         * be replaced.
         */
        INDEX((byte) 0),
        /**
         * Creates the resource. Simply adds it to the index, if there is an existing
         * document with the id, then it won't be removed.
         */
        CREATE((byte) 1);

        private final byte id;
        private final String lowercase;

        OpType(byte id) {
            this.id = id;
            this.lowercase = this.toString().toLowerCase(Locale.ENGLISH);
        }

        /**
         * The internal representation of the operation type.
         */
        public byte id() {
            return id;
        }

        public String lowercase() {
            return this.lowercase;
        }

        /**
         * Constructs the operation type from its internal representation.
         */
        public static OpType fromId(byte id) {
            if (id == 0) {
                return INDEX;
            } else if (id == 1) {
                return CREATE;
            } else {
                throw new IllegalArgumentException("No type match for [" + id + "]");
            }
        }

        public static OpType fromString(String sOpType) {
            String lowersOpType = sOpType.toLowerCase(Locale.ROOT);
            switch (lowersOpType) {
                case "create":
                    return OpType.CREATE;
                case "index":
                    return OpType.INDEX;
                default:
                    throw new IllegalArgumentException("opType [" + sOpType + "] not allowed, either [index] or [create] are allowed");
            }
        }

    }

    private String type;
    private String id;
    @Nullable
    private String routing;
    @Nullable
    private String parent;
    @Nullable
    private String timestamp;
    @Nullable
    private TimeValue ttl;

    private BytesReference source;

    private OpType opType = OpType.INDEX;

    private boolean refresh = false;
    private long version = Versions.MATCH_ANY;
    private VersionType versionType = VersionType.INTERNAL;

    private XContentType contentType = Requests.INDEX_CONTENT_TYPE;

    public IndexRequest() {
    }

    /**
     * Copy constructor that creates a new index request that is a copy of the one provided as an argument.
     * The new request will inherit though headers and context from the original request that caused it.
     */
    public IndexRequest(IndexRequest indexRequest) {
        super(indexRequest);
        this.type = indexRequest.type;
        this.id = indexRequest.id;
        this.routing = indexRequest.routing;
        this.parent = indexRequest.parent;
        this.timestamp = indexRequest.timestamp;
        this.ttl = indexRequest.ttl;
        this.source = indexRequest.source;
        this.opType = indexRequest.opType;
        this.refresh = indexRequest.refresh;
        this.version = indexRequest.version;
        this.versionType = indexRequest.versionType;
        this.contentType = indexRequest.contentType;
    }

    /**
     * Constructs a new index request against the specific index. The {@link #type(String)}
     * {@link #source(byte[])} must be set.
     */
    public IndexRequest(String index) {
        this.index = index;
    }

    /**
     * Constructs a new index request against the specific index and type. The
     * {@link #source(byte[])} must be set.
     */
    public IndexRequest(String index, String type) {
        this.index = index;
        this.type = type;
    }

    /**
     * Constructs a new index request against the index, type, id and using the source.
     *
     * @param index The index to index into
     * @param type  The type to index into
     * @param id    The id of document
     */
    public IndexRequest(String index, String type, String id) {
        this.index = index;
        this.type = type;
        this.id = id;
    }

    @Override
    public ActionRequestValidationException validate() {
        ActionRequestValidationException validationException = super.validate();
        if (type == null) {
            validationException = addValidationError("type is missing", validationException);
        }
        if (source == null) {
            validationException = addValidationError("source is missing", validationException);
        }

        if (opType() == OpType.CREATE) {
            if (versionType != VersionType.INTERNAL || version != Versions.MATCH_DELETED) {
                validationException = addValidationError("create operations do not support versioning. use index instead", validationException);
                return validationException;
            }
        }

        if (!versionType.validateVersionForWrites(version)) {
            validationException = addValidationError("illegal version value [" + version + "] for version type [" + versionType.name() + "]", validationException);
        }

        if (ttl != null) {
            if (ttl.millis() < 0) {
                validationException = addValidationError("ttl must not be negative", validationException);
            }
        }
        return validationException;
    }

    /**
     * Sets the content type that will be used when generating a document from user provided objects (like Map).
     */
    public IndexRequest contentType(XContentType contentType) {
        this.contentType = contentType;
        return this;
    }

    /**
     * The type of the indexed document.
     */
    @Override
    public String type() {
        return type;
    }

    /**
     * Sets the type of the indexed document.
     */
    public IndexRequest type(String type) {
        this.type = type;
        return this;
    }

    /**
     * The id of the indexed document. If not set, will be automatically generated.
     */
    @Override
    public String id() {
        return id;
    }

    /**
     * Sets the id of the indexed document. If not set, will be automatically generated.
     */
    public IndexRequest id(String id) {
        this.id = id;
        return this;
    }

    /**
     * Controls the shard routing of the request. Using this value to hash the shard
     * and not the id.
     */
    @Override
    public IndexRequest routing(String routing) {
        if (routing != null && routing.length() == 0) {
            this.routing = null;
        } else {
            this.routing = routing;
        }
        return this;
    }

    /**
     * Controls the shard routing of the request. Using this value to hash the shard
     * and not the id.
     */
    @Override
    public String routing() {
        return this.routing;
    }

    /**
     * Sets the parent id of this document.
     */
    public IndexRequest parent(String parent) {
        this.parent = parent;
        return this;
    }

    public String parent() {
        return this.parent;
    }

    /**
     * Sets the timestamp either as millis since the epoch, or, in the configured date format.
     */
    public IndexRequest timestamp(String timestamp) {
        this.timestamp = timestamp;
        return this;
    }

    public String timestamp() {
        return this.timestamp;
    }

    /**
     * Sets the ttl value as a time value expression.
     */
    public IndexRequest ttl(String ttl) {
        this.ttl = TimeValue.parseTimeValue(ttl, null, "ttl");
        return this;
    }

    /**
     * Sets the ttl as a {@link TimeValue} instance.
     */
    public IndexRequest ttl(TimeValue ttl) {
        this.ttl = ttl;
        return this;
    }

    /**
     * Sets the relative ttl value in milliseconds. It musts be greater than 0 as it makes little sense otherwise.
     */
    public IndexRequest ttl(long ttl) {
        this.ttl = new TimeValue(ttl);
        return this;
    }

    /**
     * Returns the ttl as a {@link TimeValue}
     */
    public TimeValue ttl() {
        return this.ttl;
    }

    /**
     * The source of the document to index, recopied to a new array if it is unsage.
     */
    public BytesReference source() {
        return source;
    }

    public Map<String, Object> sourceAsMap() {
        return XContentHelper.convertToMap(source, false).v2();
    }

    /**
     * Index the Map as a {@link org.elasticsearch.client.Requests#INDEX_CONTENT_TYPE}.
     *
     * @param source The map to index
     */
    public IndexRequest source(Map source) throws ElasticsearchGenerationException {
        return source(source, contentType);
    }

    /**
     * Index the Map as the provided content type.
     *
     * @param source The map to index
     */
    public IndexRequest source(Map source, XContentType contentType) throws ElasticsearchGenerationException {
        try {
            XContentBuilder builder = XContentFactory.contentBuilder(contentType);
            builder.map(source);
            return source(builder);
        } catch (IOException e) {
            throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
        }
    }

    /**
     * Sets the document source to index.
     *
     * Note, its preferable to either set it using {@link #source(org.elasticsearch.common.xcontent.XContentBuilder)}
     * or using the {@link #source(byte[])}.
     */
    public IndexRequest source(String source) {
        this.source = new BytesArray(source.getBytes(StandardCharsets.UTF_8));
        return this;
    }

    /**
     * Sets the content source to index.
     */
    public IndexRequest source(XContentBuilder sourceBuilder) {
        source = sourceBuilder.bytes();
        return this;
    }

    public IndexRequest source(String field1, Object value1) {
        try {
            XContentBuilder builder = XContentFactory.contentBuilder(contentType);
            builder.startObject().field(field1, value1).endObject();
            return source(builder);
        } catch (IOException e) {
            throw new ElasticsearchGenerationException("Failed to generate", e);
        }
    }

    public IndexRequest source(String field1, Object value1, String field2, Object value2) {
        try {
            XContentBuilder builder = XContentFactory.contentBuilder(contentType);
            builder.startObject().field(field1, value1).field(field2, value2).endObject();
            return source(builder);
        } catch (IOException e) {
            throw new ElasticsearchGenerationException("Failed to generate", e);
        }
    }

    public IndexRequest source(String field1, Object value1, String field2, Object value2, String field3, Object value3) {
        try {
            XContentBuilder builder = XContentFactory.contentBuilder(contentType);
            builder.startObject().field(field1, value1).field(field2, value2).field(field3, value3).endObject();
            return source(builder);
        } catch (IOException e) {
            throw new ElasticsearchGenerationException("Failed to generate", e);
        }
    }

    public IndexRequest source(String field1, Object value1, String field2, Object value2, String field3, Object value3, String field4, Object value4) {
        try {
            XContentBuilder builder = XContentFactory.contentBuilder(contentType);
            builder.startObject().field(field1, value1).field(field2, value2).field(field3, value3).field(field4, value4).endObject();
            return source(builder);
        } catch (IOException e) {
            throw new ElasticsearchGenerationException("Failed to generate", e);
        }
    }

    public IndexRequest source(Object... source) {
        if (source.length % 2 != 0) {
            throw new IllegalArgumentException("The number of object passed must be even but was [" + source.length + "]");
        }
        if (source.length == 2 && source[0] instanceof BytesReference && source[1] instanceof Boolean) {
            throw new IllegalArgumentException("you are using the removed method for source with bytes and unsafe flag, the unsafe flag was removed, please just use source(BytesReference)");
        }
        try {
            XContentBuilder builder = XContentFactory.contentBuilder(contentType);
            builder.startObject();
            for (int i = 0; i < source.length; i++) {
                builder.field(source[i++].toString(), source[i]);
            }
            builder.endObject();
            return source(builder);
        } catch (IOException e) {
            throw new ElasticsearchGenerationException("Failed to generate", e);
        }
    }

    /**
     * Sets the document to index in bytes form.
     */
    public IndexRequest source(BytesReference source) {
        this.source = source;
        return this;
    }

    /**
     * Sets the document to index in bytes form.
     */
    public IndexRequest source(byte[] source) {
        return source(source, 0, source.length);
    }

    /**
     * Sets the document to index in bytes form (assumed to be safe to be used from different
     * threads).
     *
     * @param source The source to index
     * @param offset The offset in the byte array
     * @param length The length of the data
     */
    public IndexRequest source(byte[] source, int offset, int length) {
        this.source = new BytesArray(source, offset, length);
        return this;
    }

    /**
     * Sets the type of operation to perform.
     */
    public IndexRequest opType(OpType opType) {
        this.opType = opType;
        if (opType == OpType.CREATE) {
            version(Versions.MATCH_DELETED);
            versionType(VersionType.INTERNAL);
        }
        return this;
    }

    /**
     * Sets a string representation of the {@link #opType(org.elasticsearch.action.index.IndexRequest.OpType)}. Can
     * be either "index" or "create".
     */
    public IndexRequest opType(String opType) {
        return opType(OpType.fromString(opType));
    }


    /**
     * Set to <tt>true</tt> to force this index to use {@link OpType#CREATE}.
     */
    public IndexRequest create(boolean create) {
        if (create) {
            return opType(OpType.CREATE);
        } else {
            return opType(OpType.INDEX);
        }
    }

    /**
     * The type of operation to perform.
     */
    public OpType opType() {
        return this.opType;
    }

    /**
     * Should a refresh be executed post this index operation causing the operation to
     * be searchable. Note, heavy indexing should not set this to <tt>true</tt>. Defaults
     * to <tt>false</tt>.
     */
    public IndexRequest refresh(boolean refresh) {
        this.refresh = refresh;
        return this;
    }

    public boolean refresh() {
        return this.refresh;
    }

    /**
     * Sets the version, which will cause the index operation to only be performed if a matching
     * version exists and no changes happened on the doc since then.
     */
    public IndexRequest version(long version) {
        this.version = version;
        return this;
    }

    public long version() {
        return this.version;
    }

    /**
     * Sets the versioning type. Defaults to {@link VersionType#INTERNAL}.
     */
    public IndexRequest versionType(VersionType versionType) {
        this.versionType = versionType;
        return this;
    }

    public VersionType versionType() {
        return this.versionType;
    }

    private Version getVersion(MetaData metaData, String concreteIndex) {
        // this can go away in 3.0 but is here now for easy backporting - since in 2.x we need the version on the timestamp stuff
        final IndexMetaData indexMetaData = metaData.getIndices().get(concreteIndex);
        if (indexMetaData == null) {
            throw new IndexNotFoundException(concreteIndex);
        }
        return Version.indexCreated(indexMetaData.getSettings());
    }

    public void process(MetaData metaData, @Nullable MappingMetaData mappingMd, boolean allowIdGeneration, String concreteIndex) {
        // resolve the routing if needed
        routing(metaData.resolveIndexRouting(parent, routing, index));

        // resolve timestamp if provided externally
        if (timestamp != null) {
            timestamp = MappingMetaData.Timestamp.parseStringTimestamp(timestamp,
                    mappingMd != null ? mappingMd.timestamp().dateTimeFormatter() : TimestampFieldMapper.Defaults.DATE_TIME_FORMATTER,
                    getVersion(metaData, concreteIndex));
        }
        if (mappingMd != null) {
            // might as well check for routing here
            if (mappingMd.routing().required() && routing == null) {
                throw new RoutingMissingException(concreteIndex, type, id);
            }

            if (parent != null && !mappingMd.hasParentField()) {
                throw new IllegalArgumentException("Can't specify parent if no parent field has been configured");
            }
        } else {
            if (parent != null) {
                throw new IllegalArgumentException("Can't specify parent if no parent field has been configured");
            }
        }

        // generate id if not already provided and id generation is allowed
        if (allowIdGeneration) {
            if (id == null) {
                id(Strings.base64UUID());
            }
        }

        // generate timestamp if not provided, we always have one post this stage...
        if (timestamp == null) {
            String defaultTimestamp = TimestampFieldMapper.Defaults.DEFAULT_TIMESTAMP;
            if (mappingMd != null && mappingMd.timestamp() != null) {
                // If we explicitly ask to reject null timestamp
                if (mappingMd.timestamp().ignoreMissing() != null && mappingMd.timestamp().ignoreMissing() == false) {
                    throw new TimestampParsingException("timestamp is required by mapping");
                }
                defaultTimestamp = mappingMd.timestamp().defaultTimestamp();
            }

            if (defaultTimestamp.equals(TimestampFieldMapper.Defaults.DEFAULT_TIMESTAMP)) {
                timestamp = Long.toString(System.currentTimeMillis());
            } else {
                timestamp = MappingMetaData.Timestamp.parseStringTimestamp(defaultTimestamp, mappingMd.timestamp().dateTimeFormatter(), getVersion(metaData, concreteIndex));
            }
        }
    }

    @Override
    public void readFrom(StreamInput in) throws IOException {
        super.readFrom(in);
        type = in.readString();
        id = in.readOptionalString();
        routing = in.readOptionalString();
        parent = in.readOptionalString();
        timestamp = in.readOptionalString();
        ttl = in.readBoolean() ? TimeValue.readTimeValue(in) : null;
        source = in.readBytesReference();

        opType = OpType.fromId(in.readByte());
        refresh = in.readBoolean();
        version = in.readLong();
        versionType = VersionType.fromValue(in.readByte());
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeString(type);
        out.writeOptionalString(id);
        out.writeOptionalString(routing);
        out.writeOptionalString(parent);
        out.writeOptionalString(timestamp);
        if (ttl == null) {
            out.writeBoolean(false);
        } else {
            out.writeBoolean(true);
            ttl.writeTo(out);
        }
        out.writeBytesReference(source);
        out.writeByte(opType.id());
        out.writeBoolean(refresh);
        out.writeLong(version);
        out.writeByte(versionType.getValue());
    }

    @Override
    public String toString() {
        String sSource = "_na_";
        try {
            sSource = XContentHelper.convertToJson(source, false);
        } catch (Exception e) {
            // ignore
        }
        return "index {[" + index + "][" + type + "][" + id + "], source[" + sSource + "]}";
    }
}