|
| 1 | +/* |
| 2 | + * Copyright 2008-present MongoDB, Inc. |
| 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 | + * http://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 | + |
| 17 | +package com.mongodb.client.model.search; |
| 18 | + |
| 19 | +import com.mongodb.client.AggregateIterable; |
| 20 | +import com.mongodb.client.MongoClient; |
| 21 | +import com.mongodb.client.MongoCollection; |
| 22 | +import com.mongodb.client.MongoDatabase; |
| 23 | +import com.mongodb.client.model.SearchIndexModel; |
| 24 | +import com.mongodb.internal.connection.ServerHelper; |
| 25 | +import org.bson.BsonArray; |
| 26 | +import org.bson.BsonDocument; |
| 27 | +import org.bson.Document; |
| 28 | +import org.bson.codecs.DecoderContext; |
| 29 | +import org.bson.conversions.Bson; |
| 30 | +import org.junit.jupiter.api.AfterAll; |
| 31 | +import org.junit.jupiter.api.BeforeAll; |
| 32 | +import org.junit.jupiter.api.Test; |
| 33 | + |
| 34 | +import java.util.ArrayList; |
| 35 | +import java.util.Arrays; |
| 36 | +import java.util.List; |
| 37 | +import java.util.concurrent.TimeUnit; |
| 38 | +import java.util.stream.Collectors; |
| 39 | +import java.util.stream.StreamSupport; |
| 40 | + |
| 41 | +import static com.mongodb.ClusterFixture.isAtlasSearchTest; |
| 42 | +import static com.mongodb.ClusterFixture.serverVersionAtLeast; |
| 43 | +import static com.mongodb.MongoClientSettings.getDefaultCodecRegistry; |
| 44 | +import static com.mongodb.client.Fixture.getMongoClient; |
| 45 | +import static com.mongodb.client.Fixture.getPrimary; |
| 46 | +import static com.mongodb.client.model.Aggregates.search; |
| 47 | +import static com.mongodb.client.model.Aggregates.sort; |
| 48 | +import static com.mongodb.client.model.Sorts.ascending; |
| 49 | +import static com.mongodb.client.model.search.SearchOptions.searchOptions; |
| 50 | +import static com.mongodb.client.model.search.SearchPath.fieldPath; |
| 51 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 52 | +import static org.junit.jupiter.api.Assumptions.assumeTrue; |
| 53 | + |
| 54 | +public class AggregatesSearchFunctionalTest { |
| 55 | + public static final String ATLAS_SEARCH_DATABASE = "javaVectorSearchTest"; |
| 56 | + private static MongoClient client; |
| 57 | + private static MongoDatabase database; |
| 58 | + private static MongoCollection<Document> collection; |
| 59 | + private static String searchIndexName; |
| 60 | + |
| 61 | + @BeforeAll |
| 62 | + public static void beforeAll() { |
| 63 | + assumeTrue(isAtlasSearchTest()); |
| 64 | + assumeTrue(serverVersionAtLeast(8, 0)); |
| 65 | + |
| 66 | + client = getMongoClient(); |
| 67 | + database = client.getDatabase(ATLAS_SEARCH_DATABASE); |
| 68 | + String collectionName = AggregatesSearchFunctionalTest.class.getName(); |
| 69 | + collection = database.getCollection(collectionName); |
| 70 | + collection.drop(); |
| 71 | + |
| 72 | + // We insert documents first. The ensuing indexing guarantees that all |
| 73 | + // data present at the time indexing commences will be indexed before |
| 74 | + // the index enters the READY state. |
| 75 | + insertDocuments("[\n" |
| 76 | + + " { _id: 1 },\n" |
| 77 | + + " { _id: 2, title: null },\n" |
| 78 | + + " { _id: 3, title: 'test' },\n" |
| 79 | + + " { _id: 4, title: ['test', 'xyz'] },\n" |
| 80 | + + " { _id: 5, title: 'not test' },\n" |
| 81 | + + " { _id: 6, description: 'desc 1' },\n" |
| 82 | + + " { _id: 7, description: 'desc 8' },\n" |
| 83 | + + " { _id: 8, summary: 'summary 1 one five' },\n" |
| 84 | + + " { _id: 9, summary: 'summary 2 one two three four five' },\n" |
| 85 | + + "]"); |
| 86 | + |
| 87 | + searchIndexName = "not_default"; |
| 88 | + // Index creation can take disproportionately long, so we create it once |
| 89 | + // for all tests. |
| 90 | + // We set dynamic to true to index unspecified fields. Different kinds |
| 91 | + // of fields are needed for different tests. |
| 92 | + collection.createSearchIndexes(Arrays.asList(new SearchIndexModel(searchIndexName, Document.parse( |
| 93 | + "{\n" |
| 94 | + + " \"mappings\": {\n" |
| 95 | + + " \"dynamic\": true,\n" |
| 96 | + + " \"fields\": {\n" |
| 97 | + + " \"title\": {\n" |
| 98 | + + " \"type\": \"token\"\n" |
| 99 | + + " },\n" |
| 100 | + + " \"description\": {\n" |
| 101 | + + " \"analyzer\": \"lucene.keyword\"," |
| 102 | + + " \"type\": \"string\"\n" |
| 103 | + + " }\n" |
| 104 | + + " }\n" |
| 105 | + + " }\n" |
| 106 | + + "}")))); |
| 107 | + waitForIndex(collection, searchIndexName); |
| 108 | + } |
| 109 | + |
| 110 | + @AfterAll |
| 111 | + public static void afterAll() { |
| 112 | + if (collection != null) { |
| 113 | + collection.drop(); |
| 114 | + } |
| 115 | + try { |
| 116 | + ServerHelper.checkPool(getPrimary()); |
| 117 | + } catch (InterruptedException e) { |
| 118 | + // ignore |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + @Test |
| 123 | + public void testExists() { |
| 124 | + List<Bson> pipeline = Arrays.asList( |
| 125 | + search(SearchOperator.exists(fieldPath("title")), |
| 126 | + searchOptions().index(searchIndexName))); |
| 127 | + assertResults(pipeline, "[\n" |
| 128 | + + " { _id: 2, title: null },\n" |
| 129 | + + " { _id: 3, title: 'test' },\n" |
| 130 | + + " { _id: 4, title: ['test', 'xyz'] },\n" |
| 131 | + + " { _id: 5, title: 'not test' },\n" |
| 132 | + + "]"); |
| 133 | + } |
| 134 | + |
| 135 | + @Test |
| 136 | + public void testEquals() { |
| 137 | + List<Bson> pipeline1 = Arrays.asList( |
| 138 | + search(SearchOperator.equals(fieldPath("title"), "test"), |
| 139 | + searchOptions().index(searchIndexName))); |
| 140 | + assertResults(pipeline1, "[\n" |
| 141 | + + " { _id: 3, title: 'test' }\n" |
| 142 | + + " { _id: 4, title: ['test', 'xyz'] }\n" |
| 143 | + + "]"); |
| 144 | + |
| 145 | + // equals null does not match non-existent fields |
| 146 | + List<Bson> pipeline2 = Arrays.asList( |
| 147 | + search(SearchOperator.equalsNull(fieldPath("title")), |
| 148 | + searchOptions().index(searchIndexName))); |
| 149 | + assertResults(pipeline2, "[\n" |
| 150 | + + " { _id: 2, title: null }\n" |
| 151 | + + "]"); |
| 152 | + } |
| 153 | + |
| 154 | + @Test |
| 155 | + public void testMoreLikeThis() { |
| 156 | + List<Bson> pipeline = Arrays.asList( |
| 157 | + search(SearchOperator.moreLikeThis(Document.parse("{ summary: 'summary' }").toBsonDocument()), |
| 158 | + searchOptions().index(searchIndexName))); |
| 159 | + assertResults(pipeline, "[\n" |
| 160 | + + " { _id: 8, summary: 'summary 1 one five' },\n" |
| 161 | + + " { _id: 9, summary: 'summary 2 one two three four five' },\n" |
| 162 | + + "]"); |
| 163 | + } |
| 164 | + |
| 165 | + @Test |
| 166 | + public void testRegex() { |
| 167 | + List<Bson> pipeline = Arrays.asList( |
| 168 | + search(SearchOperator.regex(fieldPath("description"), "des[c]+ <1-4>"), |
| 169 | + searchOptions().index(searchIndexName))); |
| 170 | + assertResults(pipeline, "[\n" |
| 171 | + + " { _id: 6, description: 'desc 1' },\n" |
| 172 | + + "]"); |
| 173 | + } |
| 174 | + |
| 175 | + @Test |
| 176 | + public void testWildcard() { |
| 177 | + List<Bson> pipeline = Arrays.asList( |
| 178 | + search(SearchOperator.wildcard(fieldPath("description"), "desc*"), |
| 179 | + searchOptions().index(searchIndexName))); |
| 180 | + assertResults(pipeline, "[\n" |
| 181 | + + " { _id: 6, description: 'desc 1' },\n" |
| 182 | + + " { _id: 7, description: 'desc 8' },\n" |
| 183 | + + "]"); |
| 184 | + } |
| 185 | + |
| 186 | + @Test |
| 187 | + public void testPhrase() { |
| 188 | + List<Bson> pipeline = Arrays.asList( |
| 189 | + search(SearchOperator.phrase(fieldPath("summary"), "one five").slop(2), |
| 190 | + searchOptions().index(searchIndexName))); |
| 191 | + assertResults(pipeline, "[\n" |
| 192 | + + " { _id: 8, summary: 'summary 1 one five' },\n" |
| 193 | + + "]"); |
| 194 | + } |
| 195 | + |
| 196 | + @Test |
| 197 | + public void testQueryString() { |
| 198 | + List<Bson> pipeline = Arrays.asList( |
| 199 | + search(SearchOperator.queryString(fieldPath("summary"), "summary: one AND summary: three"), |
| 200 | + searchOptions().index(searchIndexName))); |
| 201 | + assertResults(pipeline, "[\n" |
| 202 | + + " { _id: 9, summary: 'summary 2 one two three four five' },\n" |
| 203 | + + "]"); |
| 204 | + } |
| 205 | + |
| 206 | + private static void insertDocuments(final String s) { |
| 207 | + List<Document> documents = BsonArray.parse(s).stream() |
| 208 | + .map(v -> new Document(v.asDocument())) |
| 209 | + .collect(Collectors.toList()); |
| 210 | + collection.insertMany(documents); |
| 211 | + } |
| 212 | + |
| 213 | + private static void assertResults(final List<Bson> pipeline, final String expectedResultsAsString) { |
| 214 | + ArrayList<Bson> pipeline2 = new ArrayList<>(pipeline); |
| 215 | + pipeline2.add(sort(ascending("_id"))); |
| 216 | + |
| 217 | + List<BsonDocument> expectedResults = parseToList(expectedResultsAsString); |
| 218 | + List<BsonDocument> actualResults = aggregate(pipeline2); |
| 219 | + assertEquals(expectedResults, actualResults); |
| 220 | + } |
| 221 | + |
| 222 | + private static List<BsonDocument> aggregate(final List<Bson> stages) { |
| 223 | + AggregateIterable<Document> result = collection.aggregate(stages); |
| 224 | + List<BsonDocument> results = new ArrayList<>(); |
| 225 | + result.forEach(r -> results.add(r.toBsonDocument())); |
| 226 | + return results; |
| 227 | + } |
| 228 | + |
| 229 | + public static List<BsonDocument> parseToList(final String s) { |
| 230 | + return BsonArray.parse(s).stream().map(v -> toBsonDocument(v.asDocument())).collect(Collectors.toList()); |
| 231 | + } |
| 232 | + |
| 233 | + public static BsonDocument toBsonDocument(final BsonDocument bsonDocument) { |
| 234 | + return getDefaultCodecRegistry().get(BsonDocument.class).decode(bsonDocument.asBsonReader(), DecoderContext.builder().build()); |
| 235 | + } |
| 236 | + |
| 237 | + public static <T> boolean waitForIndex(final MongoCollection<T> collection, final String indexName) { |
| 238 | + long startTime = System.nanoTime(); |
| 239 | + long timeoutNanos = TimeUnit.SECONDS.toNanos(60); |
| 240 | + while (System.nanoTime() - startTime < timeoutNanos) { |
| 241 | + Document indexRecord = StreamSupport.stream(collection.listSearchIndexes().spliterator(), false) |
| 242 | + .filter(index -> indexName.equals(index.getString("name"))) |
| 243 | + .findAny().orElse(null); |
| 244 | + if (indexRecord != null) { |
| 245 | + if ("FAILED".equals(indexRecord.getString("status"))) { |
| 246 | + throw new RuntimeException("Search index has failed status."); |
| 247 | + } |
| 248 | + if (indexRecord.getBoolean("queryable")) { |
| 249 | + return true; |
| 250 | + } |
| 251 | + } |
| 252 | + try { |
| 253 | + Thread.sleep(100); // busy-wait, avoid in production |
| 254 | + } catch (InterruptedException e) { |
| 255 | + Thread.currentThread().interrupt(); |
| 256 | + throw new RuntimeException(e); |
| 257 | + } |
| 258 | + } |
| 259 | + return false; |
| 260 | + } |
| 261 | + |
| 262 | +} |
0 commit comments