Skip to content

CSHARP-5543: Add new options for Atlas Search Text and Phrase operators #1678

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
May 1, 2025
32 changes: 32 additions & 0 deletions src/MongoDB.Driver/Search/MatchCriteria.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/* Copyright 2010-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.
*/

namespace MongoDB.Driver.Search
{
/// <summary>
/// Represents the criteria used to match terms in a query for the Atlas Search Text operator.
/// </summary>
public enum MatchCriteria
{
/// <summary>
/// Match documents containing any of the terms from a query.
/// </summary>
Any,
/// <summary>
/// Match documents containing all the terms from a query.
/// </summary>
All
}
}
41 changes: 27 additions & 14 deletions src/MongoDB.Driver/Search/OperatorSearchDefinitions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -328,24 +328,26 @@ internal sealed class PhraseSearchDefinition<TDocument> : OperatorSearchDefiniti
{
private readonly SearchQueryDefinition _query;
private readonly int? _slop;
private readonly string _synonyms;

public PhraseSearchDefinition(
SearchPathDefinition<TDocument> path,
SearchQueryDefinition query,
int? slop,
SearchScoreDefinition<TDocument> score)
: base(OperatorType.Phrase, path, score)
SearchPhraseOptions<TDocument> options)
: base(OperatorType.Phrase, path, options?.Score)
{
_query = Ensure.IsNotNull(query, nameof(query));
_slop = slop;
_slop = options?.Slop;
_synonyms = options?.Synonyms;
}

private protected override BsonDocument RenderArguments(
RenderArgs<TDocument> args,
IBsonSerializer fieldSerializer) => new()
{
{ "query", _query.Render() },
{ "slop", _slop, _slop != null }
{ "slop", _slop, _slop != null },
{ "synonyms", _synonyms, _synonyms != null }
};
}

Expand Down Expand Up @@ -461,29 +463,40 @@ private protected override BsonDocument RenderArguments(
internal sealed class TextSearchDefinition<TDocument> : OperatorSearchDefinition<TDocument>
{
private readonly SearchFuzzyOptions _fuzzy;
private readonly string _matchCriteria;
private readonly SearchQueryDefinition _query;
private readonly string _synonyms;

public TextSearchDefinition(
SearchPathDefinition<TDocument> path,
SearchQueryDefinition query,
SearchFuzzyOptions fuzzy,
SearchScoreDefinition<TDocument> score,
string synonyms)
: base(OperatorType.Text, path, score)
SearchTextOptions<TDocument> options)
: base(OperatorType.Text, path, options?.Score)
{
_query = Ensure.IsNotNull(query, nameof(query));
_fuzzy = fuzzy;
_synonyms = synonyms;
_fuzzy = options?.Fuzzy;
_synonyms = options?.Synonyms;
_matchCriteria = options?.MatchCriteria switch
{
MatchCriteria.All => "all",
MatchCriteria.Any => "any",
null => null,
_ => throw new ArgumentException("Invalid match criteria set for Atlas Search text operator.")
};
}

private protected override BsonDocument RenderArguments(RenderArgs<TDocument> args,
IBsonSerializer fieldSerializer) => new()
private protected override BsonDocument RenderArguments(
RenderArgs<TDocument> args,
IBsonSerializer fieldSerializer)
{
return new BsonDocument
{
{ "query", _query.Render() },
{ "fuzzy", () => _fuzzy.Render(), _fuzzy != null },
{ "synonyms", _synonyms, _synonyms != null }
{ "synonyms", _synonyms, _synonyms != null },
{ "matchCriteria", _matchCriteria, _matchCriteria != null }
};
}
}

internal sealed class WildcardSearchDefinition<TDocument> : OperatorSearchDefinition<TDocument>
Expand Down
64 changes: 61 additions & 3 deletions src/MongoDB.Driver/Search/SearchDefinitionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,21 @@ public SearchDefinition<TDocument> Phrase(
SearchQueryDefinition query,
int? slop = null,
SearchScoreDefinition<TDocument> score = null) =>
new PhraseSearchDefinition<TDocument>(path, query, slop, score);
new PhraseSearchDefinition<TDocument>(path, query, new SearchPhraseOptions<TDocument> { Slop = slop, Score = score });

/// <summary>
/// Creates a search definition that performs search for documents containing an ordered
/// sequence of terms.
/// </summary>
/// <param name="path">The indexed field or fields to search.</param>
/// <param name="query">The string or strings to search for.</param>
/// <param name="options">The options.</param>
/// <returns>A phrase search definition.</returns>
public SearchDefinition<TDocument> Phrase(
SearchPathDefinition<TDocument> path,
SearchQueryDefinition query,
SearchPhraseOptions<TDocument> options) =>
new PhraseSearchDefinition<TDocument>(path, query, options);

/// <summary>
/// Creates a search definition that performs search for documents containing an ordered
Expand All @@ -569,6 +583,21 @@ public SearchDefinition<TDocument> Phrase<TField>(
SearchScoreDefinition<TDocument> score = null) =>
Phrase(new ExpressionFieldDefinition<TDocument>(path), query, slop, score);

/// <summary>
/// Creates a search definition that performs search for documents containing an ordered
/// sequence of terms.
/// </summary>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="path">The indexed field or fields to search.</param>
/// <param name="query">The string or strings to search for.</param>
/// <param name="options">The options.</param>
/// <returns>A phrase search definition.</returns>
public SearchDefinition<TDocument> Phrase<TField>(
Expression<Func<TDocument, TField>> path,
SearchQueryDefinition query,
SearchPhraseOptions<TDocument> options) =>
Phrase(new ExpressionFieldDefinition<TDocument>(path), query, options);

/// <summary>
/// Creates a search definition that queries a combination of indexed fields and values.
/// </summary>
Expand Down Expand Up @@ -732,6 +761,20 @@ public SearchDefinition<TDocument> Regex<TField>(
public SearchDefinition<TDocument> Span(SearchSpanDefinition<TDocument> clause) =>
new SpanSearchDefinition<TDocument>(clause);

/// <summary>
/// Creates a search definition that performs full-text search using the analyzer specified
/// in the index configuration.
/// </summary>
/// <param name="path">The indexed field or fields to search.</param>
/// <param name="query">The string or strings to search for.</param>
/// <param name="options">The options.</param>
/// <returns>A text search definition.</returns>
public SearchDefinition<TDocument> Text(
SearchPathDefinition<TDocument> path,
SearchQueryDefinition query,
SearchTextOptions<TDocument> options) =>
new TextSearchDefinition<TDocument>(path, query, options);

/// <summary>
/// Creates a search definition that performs full-text search using the analyzer specified
/// in the index configuration.
Expand All @@ -746,7 +789,7 @@ public SearchDefinition<TDocument> Text(
SearchQueryDefinition query,
SearchFuzzyOptions fuzzy = null,
SearchScoreDefinition<TDocument> score = null) =>
new TextSearchDefinition<TDocument>(path, query, fuzzy, score, null);
new TextSearchDefinition<TDocument>(path, query, new SearchTextOptions<TDocument> { Fuzzy = fuzzy, Score = score });

/// <summary>
/// Creates a search definition that performs full-text search with synonyms using the analyzer specified
Expand All @@ -762,7 +805,22 @@ public SearchDefinition<TDocument> Text(
SearchQueryDefinition query,
string synonyms,
SearchScoreDefinition<TDocument> score = null) =>
new TextSearchDefinition<TDocument>(path, query, null, score, synonyms);
new TextSearchDefinition<TDocument>(path, query, new SearchTextOptions<TDocument> { Score = score, Synonyms = synonyms });

/// <summary>
/// Creates a search definition that performs full-text search using the analyzer specified
/// in the index configuration.
/// </summary>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="path">The indexed field or field to search.</param>
/// <param name="query">The string or strings to search for.</param>
/// <param name="options">The options.</param>
/// <returns>A text search definition.</returns>
public SearchDefinition<TDocument> Text<TField>(
Expression<Func<TDocument, TField>> path,
SearchQueryDefinition query,
SearchTextOptions<TDocument> options) =>
Text(new ExpressionFieldDefinition<TDocument>(path), query, options);

/// <summary>
/// Creates a search definition that performs full-text search using the analyzer specified
Expand Down
38 changes: 38 additions & 0 deletions src/MongoDB.Driver/Search/SearchPhraseOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/* Copyright 2010-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.
*/

namespace MongoDB.Driver.Search
{
/// <summary>
/// Options for atlas search phrase operator.
/// </summary>
public sealed class SearchPhraseOptions<TDocument>
{
/// <summary>
/// The score modifier.
/// </summary>
public SearchScoreDefinition<TDocument> Score { get; set; }

/// <summary>
/// The allowable distance between words in the query phrase.
/// </summary>
public int? Slop { get; set; }

/// <summary>
/// The name of the synonym mapping definition in the index definition. Value can't be an empty string (e.g. "").
/// </summary>
public string Synonyms { get; set; }
}
}
44 changes: 44 additions & 0 deletions src/MongoDB.Driver/Search/SearchTextOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/* Copyright 2010-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.
*/

namespace MongoDB.Driver.Search
{
/// <summary>
/// Options for atlas search text operator.
/// </summary>
public sealed class SearchTextOptions<TDocument>
{
/// <summary>
/// The options for fuzzy search.
/// </summary>
public SearchFuzzyOptions Fuzzy { get; set; }

/// <summary>
/// The criteria to use to match the terms in the query. Value can be either "any" or "all".
/// Defaults to "all" if omitted.
/// </summary>
public MatchCriteria? MatchCriteria { get; set; }

/// <summary>
/// The score modifier.
/// </summary>
public SearchScoreDefinition<TDocument> Score { get; set; }

/// <summary>
/// The name of the synonym mapping definition in the index definition. Value can't be an empty string (e.g. "").
/// </summary>
public string Synonyms { get; set; }
Copy link
Member

Choose a reason for hiding this comment

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

xml-docs says: Value can't be an empty string. Should we enforce this condition?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Similar to my other comment I prefer letting the server error rather than enforcing the condition in the driver. Yes, it's simple but I don't think the driver should be doing that much hand holding.

Copy link
Member

Choose a reason for hiding this comment

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

If we letting server to decide, why do we have it in XML docs then? =)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It's in the XML docs because I mirrored the official docs and it's mentioned there. I didn't think much of it.

}
}
40 changes: 40 additions & 0 deletions tests/MongoDB.Driver.Tests/Search/AtlasSearchTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,26 @@ public void PhraseAnalyzerPath()
result.Title.Should().Be("Declaration of Independence");
}

[Fact]
public void PhraseSynonym()
{
var result =
GetSynonymTestCollection().Aggregate()
.Search(
Builders<Movie>.Search.Phrase("plot", "automobile race", new SearchPhraseOptions<Movie> { Synonyms = "transportSynonyms" }),
indexName: "synonyms-tests")
.Project<Movie>(Builders<Movie>.Projection.Include("Title").Exclude("_id"))
.Limit(5)
.ToList();

result.Count.Should().Be(5);
result[0].Title.Should().Be("The Great Race");
result[1].Title.Should().Be("The Cannonball Run");
result[2].Title.Should().Be("National Mechanics");
result[3].Title.Should().Be("Genevieve");
result[4].Title.Should().Be("Speedway Junky");
}

[Fact]
public void PhraseWildcardPath()
{
Expand Down Expand Up @@ -723,6 +743,26 @@ public void Text()
result.Title.Should().Be("Declaration of Independence");
}

[Fact]
public void TextMatchCriteria()
{
var result =
GetSynonymTestCollection().Aggregate()
.Search(
Builders<Movie>.Search.Text("plot", "attire", new SearchTextOptions<Movie> { Synonyms = "attireSynonyms", MatchCriteria = MatchCriteria.Any}),
indexName: "synonyms-tests")
.Project<Movie>(Builders<Movie>.Projection.Include("Title").Exclude("_id"))
.Limit(5)
.ToList();

result.Count.Should().Be(5);
result[0].Title.Should().Be("The Royal Tailor");
result[1].Title.Should().Be("La guerre des tuques");
result[2].Title.Should().Be("The Dress");
result[3].Title.Should().Be("The Club");
result[4].Title.Should().Be("The Triple Echo");
}

[Theory]
[InlineData("automobile", "transportSynonyms", "Blue Car")]
[InlineData("boat", "transportSynonyms", "And the Ship Sails On")]
Expand Down
Loading