|
| 1 | +/* |
| 2 | + * Copyright 2016-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 | + * Gateway to {@literal sampling expressions} that match documents using a provided criteria. |
| 23 | + * |
| 24 | + * @author James McNee |
| 25 | + * @since 3.2.4 |
| 26 | + */ |
| 27 | +public class SamplingOperators { |
| 28 | + |
| 29 | + /** |
| 30 | + * Encapsulates the aggregation framework {@code $sampleRate} operator. |
| 31 | + * |
| 32 | + * @author James McNee |
| 33 | + * @see <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sampleRate/"> |
| 34 | + * https://docs.mongodb.com/manual/reference/operator/aggregation/sampleRate/</a> |
| 35 | + */ |
| 36 | + public static class SampleRate implements MatchExpression { |
| 37 | + |
| 38 | + private final double sampleRate; |
| 39 | + |
| 40 | + private SampleRate(double sampleRate) { |
| 41 | + this.sampleRate = sampleRate; |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Creates new {@link SamplingOperators.SampleRate}. |
| 46 | + * |
| 47 | + * @param sampleRate sample rate to determine number of documents to be randomly selected from the input. |
| 48 | + * @return new instance of {@link SamplingOperators.SampleRate}. |
| 49 | + */ |
| 50 | + public static SampleRate sampleRate(double sampleRate) { |
| 51 | + Assert.isTrue(sampleRate >= 0, "Sample rate must be greater than zero!"); |
| 52 | + Assert.isTrue(sampleRate <= 1, "Sample rate must not be greater than one!"); |
| 53 | + |
| 54 | + return new SampleRate(sampleRate); |
| 55 | + } |
| 56 | + |
| 57 | + @Override |
| 58 | + public Document toDocument(AggregationOperationContext context) { |
| 59 | + return new Document("$sampleRate", sampleRate); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments