|
| 1 | +/* |
| 2 | + * Copyright 2017-2021 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package org.springframework.data.mongodb.core.aggregation; |
| 17 | + |
| 18 | +import org.bson.Document; |
| 19 | +import org.springframework.util.Assert; |
| 20 | + |
| 21 | +/** |
| 22 | + * Encapsulates the {@code $sampleRate}-operation. |
| 23 | + * <p> |
| 24 | + * We recommend using the static factory method {@link Aggregation#sampleRate(double)} instead of creating instances of this |
| 25 | + * class directly. |
| 26 | + * |
| 27 | + * @author James McNee |
| 28 | + * @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sampleRate/">MongoDB Aggregation Framework: |
| 29 | + * $sampleRate</a> |
| 30 | + * @since 3.2.4 |
| 31 | + */ |
| 32 | +public class SampleRateOperation implements AggregationOperation { |
| 33 | + |
| 34 | + private final double sampleRate; |
| 35 | + |
| 36 | + /** |
| 37 | + * @param sampleRate sample rate to determine number of documents to be randomly selected from the input. |
| 38 | + */ |
| 39 | + public SampleRateOperation(double sampleRate) { |
| 40 | + Assert.isTrue(sampleRate >= 0, "Sample rate must be greater than zero!"); |
| 41 | + Assert.isTrue(sampleRate <= 1, "Sample rate must not be greater than one!"); |
| 42 | + this.sampleRate = sampleRate; |
| 43 | + } |
| 44 | + |
| 45 | + /* |
| 46 | + (non-Javadoc) |
| 47 | + * @see org.springframework.data.mongodb.core.aggregation.BucketOperationSupport#toDocument(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) |
| 48 | + */ |
| 49 | + @Override |
| 50 | + public Document toDocument(AggregationOperationContext context) { |
| 51 | + return new Document(getOperator(), this.sampleRate); |
| 52 | + } |
| 53 | + |
| 54 | + /* |
| 55 | + * (non-Javadoc) |
| 56 | + * @see org.springframework.data.mongodb.core.aggregation.AggregationOperation#getOperator() |
| 57 | + */ |
| 58 | + @Override |
| 59 | + public String getOperator() { |
| 60 | + return "$sampleRate"; |
| 61 | + } |
| 62 | +} |
0 commit comments