Skip to content

Commit

Permalink
Add regex operator to Atlas Search (#1587)
Browse files Browse the repository at this point in the history
Add regex operator to Atlas Search

There are several Atlas Search query operators that are not implemented with first class support in the Java driver. This PR adds the regex operator to Atlas Search.

JAVA-5726
  • Loading branch information
joykim1005 authored Jan 16, 2025
1 parent 0922a24 commit e022dbd
Show file tree
Hide file tree
Showing 7 changed files with 148 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* 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.search;

import com.mongodb.annotations.Beta;
import com.mongodb.annotations.Reason;
import com.mongodb.annotations.Sealed;

/**
* @see SearchOperator#regex(SearchPath, String)
* @see SearchOperator#regex(Iterable, Iterable)
* @since 5.3
*/

@Sealed
@Beta(Reason.CLIENT)
public interface RegexSearchOperator extends SearchOperator {
@Override
RegexSearchOperator score(SearchScore modifier);
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
final class SearchConstructibleBsonElement extends AbstractConstructibleBsonElement<SearchConstructibleBsonElement> implements
MustCompoundSearchOperator, MustNotCompoundSearchOperator, ShouldCompoundSearchOperator, FilterCompoundSearchOperator,
ExistsSearchOperator, TextSearchOperator, AutocompleteSearchOperator,
NumberNearSearchOperator, DateNearSearchOperator, GeoNearSearchOperator,
NumberNearSearchOperator, DateNearSearchOperator, GeoNearSearchOperator, RegexSearchOperator,
ValueBoostSearchScore, PathBoostSearchScore, ConstantSearchScore, FunctionSearchScore,
GaussSearchScoreExpression, PathSearchScoreExpression,
FacetSearchCollector,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,36 @@ static PhraseSearchOperator phrase(final Iterable<? extends SearchPath> paths, f
.append("query", queryIterator.hasNext() ? queries : firstQuery));
}

/**
* Returns a {@link SearchOperator} that performs a search using a regular expression.
*
* @param path The field to be searched.
* @param query The string to search for.
* @return The requested {@link SearchOperator}.
* @mongodb.atlas.manual atlas-search/regex/ regex operator
*/
static RegexSearchOperator regex(final SearchPath path, final String query) {
return regex(singleton(notNull("path", path)), singleton(notNull("query", query)));
}

/**
* Returns a {@link SearchOperator} that performs a search using a regular expression.
*
* @param paths The non-empty fields to be searched.
* @param queries The non-empty strings to search for.
* @return The requested {@link SearchOperator}.
* @mongodb.atlas.manual atlas-search/regex/ regex operator
*/
static RegexSearchOperator regex(final Iterable<? extends SearchPath> paths, final Iterable<String> queries) {
Iterator<? extends SearchPath> pathIterator = notNull("paths", paths).iterator();
isTrueArgument("paths must not be empty", pathIterator.hasNext());
Iterator<String> queryIterator = notNull("queries", queries).iterator();
isTrueArgument("queries must not be empty", queryIterator.hasNext());
String firstQuery = queryIterator.next();
return new SearchConstructibleBsonElement("regex", new Document("path", combineToBsonValue(pathIterator, false))
.append("query", queryIterator.hasNext() ? queries : firstQuery));
}

/**
* Creates a {@link SearchOperator} from a {@link Bson} in situations when there is no builder method that better satisfies your needs.
* This method cannot be used to validate the syntax.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
import static com.mongodb.client.model.search.SearchOperator.exists;
import static com.mongodb.client.model.search.SearchOperator.near;
import static com.mongodb.client.model.search.SearchOperator.numberRange;
import static com.mongodb.client.model.search.SearchOperator.regex;
import static com.mongodb.client.model.search.SearchOperator.phrase;
import static com.mongodb.client.model.search.SearchOperator.text;
import static com.mongodb.client.model.search.SearchOptions.searchOptions;
Expand Down Expand Up @@ -610,7 +611,8 @@ private static Stream<Arguments> searchAndSearchMetaArgs() {
.lte(Instant.ofEpochMilli(1)),
near(0, 1.5, fieldPath("fieldName7"), fieldPath("fieldName8")),
near(Instant.ofEpochMilli(1), Duration.ofMillis(3), fieldPath("fieldName9")),
phrase(fieldPath("fieldName10"), "term6")
phrase(fieldPath("fieldName10"), "term6"),
regex(fieldPath("fieldName11"), "term7")
))
.minimumShouldMatch(1)
.mustNot(singleton(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,58 @@ void phrase() {
);
}

@Test
void regex() {
assertAll(
() -> assertThrows(IllegalArgumentException.class, () ->
// queries must not be empty
SearchOperator.regex(singleton(fieldPath("fieldName")), emptyList())
),
() -> assertThrows(IllegalArgumentException.class, () ->
// paths must not be empty
SearchOperator.regex(emptyList(), singleton("term"))
),
() -> assertEquals(
new BsonDocument("regex",
new BsonDocument("path", fieldPath("fieldName").toBsonValue())
.append("query", new BsonString("term"))
),
SearchOperator.regex(
fieldPath("fieldName"),
"term")
.toBsonDocument()
),
() -> assertEquals(
new BsonDocument("regex",
new BsonDocument("path", fieldPath("fieldName").toBsonValue())
.append("query", new BsonString("term"))
),
SearchOperator.regex(
singleton(fieldPath("fieldName")),
singleton("term"))
.toBsonDocument()
),
() -> assertEquals(
new BsonDocument("regex",
new BsonDocument("path", new BsonArray(asList(
fieldPath("fieldName").toBsonValue(),
wildcardPath("wildc*rd").toBsonValue())))
.append("query", new BsonArray(asList(
new BsonString("term1"),
new BsonString("term2"))))
),
SearchOperator.regex(
asList(
fieldPath("fieldName"),
wildcardPath("wildc*rd")),
asList(
"term1",
"term2"))
.toBsonDocument()
)
);
}

private static SearchOperator docExamplePredefined() {
return SearchOperator.exists(
fieldPath("fieldName"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,27 @@ object SearchOperator {
def phrase(paths: Iterable[_ <: SearchPath], queries: Iterable[String]): PhraseSearchOperator =
JSearchOperator.phrase(paths.asJava, queries.asJava)

/**
* Returns a `SearchOperator` that performs a search using a regular expression.
*
* @param path The field to be searched.
* @param query The string to search for.
* @return The requested `SearchOperator`.
* @see [[https://www.mongodb.com/docs/atlas/atlas-search/regex/ regex operator]]
*/
def regex(path: SearchPath, query: String): RegexSearchOperator = JSearchOperator.regex(path, query)

/**
* Returns a `SearchOperator` that performs a search using a regular expression.
*
* @param paths The non-empty fields to be searched.
* @param queries The non-empty strings to search for.
* @return The requested `SearchOperator`.
* @see [[https://www.mongodb.com/docs/atlas/atlas-search/regex/ regex operator]]
*/
def regex(paths: Iterable[_ <: SearchPath], queries: Iterable[String]): RegexSearchOperator =
JSearchOperator.regex(paths.asJava, queries.asJava)

/**
* Creates a `SearchOperator` from a `Bson` in situations when there is no builder method that better satisfies your needs.
* This method cannot be used to validate the syntax.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,14 @@ package object search {
@Beta(Array(Reason.CLIENT))
type AutocompleteSearchOperator = com.mongodb.client.model.search.AutocompleteSearchOperator

/**
* @see `SearchOperator.regex(String, SearchPath)`
* @see `SearchOperator.regex(Iterable, Iterable)`
*/
@Sealed
@Beta(Array(Reason.CLIENT))
type RegexSearchOperator = com.mongodb.client.model.search.RegexSearchOperator

/**
* A base for a [[NumberRangeSearchOperatorBase]] which allows creating instances of this operator.
* This interface is a technicality and does not represent a meaningful element of the full-text search query syntax.
Expand Down

0 comments on commit e022dbd

Please sign in to comment.