Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions driver-core/src/main/com/mongodb/client/model/Aggregates.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
import static com.mongodb.assertions.Assertions.isTrueArgument;
import static com.mongodb.assertions.Assertions.notNull;
import static com.mongodb.client.model.GeoNearOptions.geoNearOptions;
import static com.mongodb.client.model.ScoreOptions.scoreOptions;
import static com.mongodb.client.model.densify.DensifyOptions.densifyOptions;
import static com.mongodb.client.model.search.SearchOptions.searchOptions;
import static com.mongodb.internal.Iterables.concat;
Expand Down Expand Up @@ -1093,6 +1094,68 @@ public static Bson rerank(
return new RerankBson(query, paths, numDocsToRerank, model);
}

/**
* Creates a {@code $score} pipeline stage that computes a new score for each document
* and attaches it as {@code score} metadata.
* You may use the {@code $meta: "score"} expression to extract the computed score.
*
* @param score the expression that computes the score. Must evaluate to a numeric value.
* @param <TExpression> the score expression type
* @return the {@code $score} pipeline stage
* @mongodb.driver.manual reference/operator/aggregation/score/ $score
* @mongodb.server.release 8.2
* @since 5.10
*/
public static <TExpression> Bson score(final TExpression score) {
return score(score, scoreOptions());
}

/**
* Creates a {@code $score} pipeline stage that computes a new score for each document
* and attaches it as {@code score} metadata, with optional normalization, weighting and score details.
* You may use the {@code $meta: "score"} expression to extract the computed score.
*
* @param score the expression that computes the score. Must evaluate to a numeric value.
* @param options optional {@code $score} pipeline stage fields
* @param <TExpression> the score expression type
* @return the {@code $score} pipeline stage
* @mongodb.driver.manual reference/operator/aggregation/score/ $score
* @mongodb.server.release 8.2
* @since 5.10
*/
public static <TExpression> Bson score(final TExpression score, final ScoreOptions options) {
notNull("score", score);
notNull("options", options);
return new Bson() {
@Override
public <TDocument> BsonDocument toBsonDocument(final Class<TDocument> documentClass, final CodecRegistry codecRegistry) {
BsonDocumentWriter writer = new BsonDocumentWriter(new BsonDocument());
writer.writeStartDocument();
writer.writeStartDocument("$score");

writer.writeName("score");
BuildersHelper.encodeValue(writer, score, codecRegistry);

options.toBsonDocument(documentClass, codecRegistry).forEach((optionName, optionValue) -> {
writer.writeName(optionName);
BuildersHelper.encodeValue(writer, optionValue, codecRegistry);
});

writer.writeEndDocument();
writer.writeEndDocument();
return writer.getDocument();
}

@Override
public String toString() {
return "Stage{name='$score'"
+ ", score=" + score
+ ", options=" + options
+ '}';
}
};
}

/**
* Creates an $unset pipeline stage that removes/excludes fields from documents
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed 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 com.mongodb.client.model;

import com.mongodb.annotations.Immutable;
import com.mongodb.internal.client.model.AbstractConstructibleBson;
import org.bson.BsonDocument;
import org.bson.Document;
import org.bson.conversions.Bson;

import static com.mongodb.assertions.Assertions.isTrueArgument;
import static com.mongodb.assertions.Assertions.notNull;

final class ScoreConstructibleBson extends AbstractConstructibleBson<ScoreConstructibleBson> implements ScoreOptions {
/**
* An {@linkplain Immutable immutable} {@link BsonDocument#isEmpty() empty} instance.
*/
static final ScoreOptions EMPTY_IMMUTABLE = new ScoreConstructibleBson(AbstractConstructibleBson.EMPTY_IMMUTABLE);

private ScoreConstructibleBson(final Bson base) {
super(base);
}

private ScoreConstructibleBson(final Bson base, final Document appended) {
super(base, appended);
}

@Override
public ScoreOptions normalization(final ScoreNormalization normalization) {
notNull("normalization", normalization);
return newAppended("normalization", normalization.getValue());
}

@Override
public ScoreOptions weight(final double weight) {
isTrueArgument("weight must be in the range [0, 1]", weight >= 0 && weight <= 1);
return newAppended("weight", weight);
}

@Override
public ScoreOptions scoreDetails(final boolean scoreDetails) {
return newAppended("scoreDetails", scoreDetails);
}

@Override
protected ScoreConstructibleBson newSelf(final Bson base, final Document appended) {
return new ScoreConstructibleBson(base, appended);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed 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 com.mongodb.client.model;

/**
* Normalization methods for the {@link Aggregates#score(Object, ScoreOptions) $score}
* and {@code $scoreFusion} pipeline stages.
*
* @mongodb.driver.manual reference/operator/aggregation/score/ $score
* @mongodb.driver.manual reference/operator/aggregation/scoreFusion/ $scoreFusion
* @mongodb.server.release 8.2
* @since 5.10
*/
public enum ScoreNormalization {
/**
* No normalization is applied.
*/
NONE("none"),
Comment thread
rozza marked this conversation as resolved.
/**
* Normalizes the score to the range (0, 1) by applying the sigmoid function.
*/
SIGMOID("sigmoid"),
/**
* Normalizes the score to the range [0, 1] by applying min-max scaling.
*/
MIN_MAX_SCALER("minMaxScaler");

private final String value;

ScoreNormalization(final String value) {
this.value = value;
}

/**
* Returns the value as expected by the server.
*
* @return the server value
*/
public String getValue() {
return value;
}
}
70 changes: 70 additions & 0 deletions driver-core/src/main/com/mongodb/client/model/ScoreOptions.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright 2008-present MongoDB, Inc.
*
* Licensed 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 com.mongodb.client.model;

import org.bson.conversions.Bson;

/**
* The options for a {@link Aggregates#score(Object, ScoreOptions) $score} pipeline stage.
*
* @mongodb.driver.manual reference/operator/aggregation/score/ $score
* @mongodb.server.release 8.2
* @since 5.10
*/
public interface ScoreOptions extends Bson {
/**
* Returns {@link ScoreOptions} that represents server defaults.
*
* @return {@link ScoreOptions} that represents server defaults.
*/
static ScoreOptions scoreOptions() {
return ScoreConstructibleBson.EMPTY_IMMUTABLE;
}

/**
* The method used to normalize the score to the range [0, 1].
* If this option is not provided, the server default is {@link ScoreNormalization#NONE}.
*
* @param normalization the normalization method
* @return a new {@link ScoreOptions} with the provided option set
* @since 5.10
*/
ScoreOptions normalization(ScoreNormalization normalization);

/**
* The factor to multiply the score by after normalization.
* Must be in the range [0, 1].
Comment thread
rozza marked this conversation as resolved.
*
* @param weight the weight
* @return a new {@link ScoreOptions} with the provided option set
* @throws IllegalArgumentException if the weight is not in the range [0, 1]
* @mongodb.driver.manual reference/operator/aggregation/score/ $score
* @since 5.10
*/
ScoreOptions weight(double weight);

/**
* Specifies whether to populate the {@code scoreDetails} metadata field,
* which contains details on how the score was computed.
* If this option is not provided, the server default is {@code false}.
*
* @param scoreDetails whether to populate the {@code scoreDetails} metadata field
* @return a new {@link ScoreOptions} with the provided option set
* @since 5.10
*/
ScoreOptions scoreDetails(boolean scoreDetails);
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.MethodSource;

import java.math.RoundingMode;
Expand All @@ -43,10 +44,12 @@
import static com.mongodb.client.model.Aggregates.geoNear;
import static com.mongodb.client.model.Aggregates.group;
import static com.mongodb.client.model.Aggregates.rerank;
import static com.mongodb.client.model.Aggregates.score;
import static com.mongodb.client.model.Aggregates.unset;
import static com.mongodb.client.model.Aggregates.vectorSearch;
import static com.mongodb.client.model.RerankQuery.rerankQuery;
import static com.mongodb.client.model.GeoNearOptions.geoNearOptions;
import static com.mongodb.client.model.ScoreOptions.scoreOptions;
import static com.mongodb.client.model.Sorts.ascending;
import static com.mongodb.client.model.Windows.Bound.UNBOUNDED;
import static com.mongodb.client.model.Windows.documents;
Expand All @@ -57,6 +60,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

public class AggregatesTest extends OperationTest {
Expand Down Expand Up @@ -453,4 +457,84 @@ public void testRerankWithMultiplePathsAndBsonQuery() {
"rerank-2"
));
}

@Test
public void testScoreWithExpression() {
assertPipeline(
"{'$score': {'score': {'$multiply': ['$rating', 2]}}}",
score(new Document("$multiply", asList("$rating", 2))));
}

@Test
public void testScoreWithAllOptions() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Request: Adding tests for all normalization types to protect against accidential regressions.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added two test cases that inject all enum values

  1. testScoreWithEachNormalization
  2. testScoreOnServerWithEachNormalization

assertPipeline(
"{"
+ " '$score': {"
+ " 'score': '$rating',"
+ " 'normalization': 'sigmoid',"
+ " 'weight': 0.5,"
+ " 'scoreDetails': true"
+ " }"
+ "}",
score("$rating", scoreOptions()
.normalization(ScoreNormalization.SIGMOID)
.weight(0.5)
.scoreDetails(true)));
}

@ParameterizedTest
@EnumSource(ScoreNormalization.class)
public void testScoreWithEachNormalization(final ScoreNormalization normalization) {
assertPipeline(
"{'$score': {'score': '$rating', 'normalization': '" + normalization.getValue() + "'}}",
score("$rating", scoreOptions().normalization(normalization)));
}

@Test
public void testScoreWeightValidation() {
assertThrows(IllegalArgumentException.class, () -> scoreOptions().weight(-0.1));
assertThrows(IllegalArgumentException.class, () -> scoreOptions().weight(1.1));
assertThrows(IllegalArgumentException.class, () -> scoreOptions().weight(Double.NaN));
assertPipeline(
"{'$score': {'score': '$rating', 'weight': 0.0}}",
score("$rating", scoreOptions().weight(0)));
assertPipeline(
"{'$score': {'score': '$rating', 'weight': 1.0}}",
score("$rating", scoreOptions().weight(1)));
}

@Test
public void testScore() {
assumeTrue(serverVersionAtLeast(8, 2));
getCollectionHelper().insertDocuments("[{_id: 1, rating: 2}, {_id: 2, rating: 4}]");

List<Bson> pipeline = asList(
score(new Document("$multiply", asList("$rating", 2)),
scoreOptions().normalization(ScoreNormalization.SIGMOID)),
Aggregates.sort(ascending("_id")),
Aggregates.project(Projections.computed("score", new Document("$meta", "score"))));

List<BsonDocument> results = getCollectionHelper().aggregate(pipeline);
assertEquals(2, results.size());
// sigmoid normalization maps each score into the range (0, 1)
results.forEach(result -> {
double scoreValue = result.getNumber("score").doubleValue();
Assertions.assertTrue(scoreValue > 0 && scoreValue < 1);
});
}

@ParameterizedTest
@EnumSource(ScoreNormalization.class)
public void testScoreOnServerWithEachNormalization(final ScoreNormalization normalization) {
Comment thread
rozza marked this conversation as resolved.
assumeTrue(serverVersionAtLeast(8, 2));
getCollectionHelper().insertDocuments("[{_id: 1, rating: 2}, {_id: 2, rating: 4}]");

List<Bson> pipeline = asList(
score("$rating", scoreOptions().normalization(normalization)),
Aggregates.project(Projections.computed("score", new Document("$meta", "score"))));

List<BsonDocument> results = getCollectionHelper().aggregate(pipeline);
assertEquals(2, results.size());
results.forEach(result -> Assertions.assertTrue(result.isNumber("score")));
}
}
Loading