Skip to content

Commit 7be2b8f

Browse files
committed
Added support for dropping an index by its keys.
JAVA-1714
1 parent 0dd6d1f commit 7be2b8f

File tree

11 files changed

+149
-32
lines changed

11 files changed

+149
-32
lines changed

driver-async/src/main/com/mongodb/async/client/MongoCollection.java

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -519,14 +519,23 @@ void bulkWrite(List<? extends WriteModel<? extends TDocument>> requests, BulkWri
519519
<TResult> ListIndexesIterable<TResult> listIndexes(Class<TResult> resultClass);
520520

521521
/**
522-
* Drops the given index.
522+
* Drops the index given its name.
523523
*
524524
* @param indexName the name of the index to remove
525525
* @param callback the callback that is completed once the index has been dropped
526526
* @mongodb.driver.manual reference/command/dropIndexes/ Drop indexes
527527
*/
528528
void dropIndex(String indexName, SingleResultCallback<Void> callback);
529529

530+
/**
531+
* Drops the index given the keys used to create it.
532+
*
533+
* @param keys the keys of the index to remove
534+
* @param callback the callback that is completed once the index has been dropped
535+
* @mongodb.driver.manual reference/command/dropIndexes/ Drop indexes
536+
*/
537+
void dropIndex(Bson keys, SingleResultCallback<Void> callback);
538+
530539
/**
531540
* Drop all the indexes on this collection, except for the default on _id.
532541
*

driver-async/src/main/com/mongodb/async/client/MongoCollectionImpl.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -469,6 +469,11 @@ public void dropIndex(final String indexName, final SingleResultCallback<Void> c
469469
executor.execute(new DropIndexOperation(namespace, indexName), callback);
470470
}
471471

472+
@Override
473+
public void dropIndex(final Bson keys, final SingleResultCallback<Void> callback) {
474+
executor.execute(new DropIndexOperation(namespace, keys.toBsonDocument(BsonDocument.class, codecRegistry)), callback);
475+
}
476+
472477
@Override
473478
public void dropIndexes(final SingleResultCallback<Void> callback) {
474479
dropIndex("*", callback);

driver-async/src/test/unit/com/mongodb/async/client/MongoCollectionSpecification.groovy

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -890,18 +890,29 @@ class MongoCollectionSpecification extends Specification {
890890

891891
def 'should use DropIndexOperation correctly for dropIndex'() {
892892
given:
893-
def executor = new TestOperationExecutor([null])
893+
def executor = new TestOperationExecutor([null, null])
894894
def collection = new MongoCollectionImpl(namespace, Document, codecRegistry, readPreference, writeConcern, executor)
895-
def expectedOperation = new DropIndexOperation(namespace, 'indexName')
896-
def futureResultCallback = new FutureResultCallback<Void>()
897895

898896
when:
897+
def expectedOperation = new DropIndexOperation(namespace, 'indexName')
898+
def futureResultCallback = new FutureResultCallback<Void>()
899899
collection.dropIndex('indexName', futureResultCallback)
900900
futureResultCallback.get()
901901
def operation = executor.getWriteOperation() as DropIndexOperation
902902

903903
then:
904904
expect operation, isTheSameAs(expectedOperation)
905+
906+
when:
907+
def keys = new BsonDocument('x', new BsonInt32(1))
908+
expectedOperation = new DropIndexOperation(namespace, keys)
909+
futureResultCallback = new FutureResultCallback<Void>()
910+
collection.dropIndex(keys, futureResultCallback)
911+
futureResultCallback.get()
912+
operation = executor.getWriteOperation() as DropIndexOperation
913+
914+
then:
915+
expect operation, isTheSameAs(expectedOperation)
905916
}
906917

907918
def 'should use DropIndexOperation correctly for dropIndexes'() {

driver-core/src/main/com/mongodb/operation/CreateIndexesOperation.java

Lines changed: 1 addition & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@
3838
import org.bson.BsonInt32;
3939
import org.bson.BsonInt64;
4040
import org.bson.BsonString;
41-
import org.bson.BsonValue;
4241

4342
import java.util.ArrayList;
4443
import java.util.List;
@@ -48,6 +47,7 @@
4847
import static com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback;
4948
import static com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol;
5049
import static com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocolAsync;
50+
import static com.mongodb.operation.IndexHelper.generateIndexName;
5151
import static com.mongodb.operation.OperationHelper.AsyncCallableWithConnection;
5252
import static com.mongodb.operation.OperationHelper.CallableWithConnection;
5353
import static com.mongodb.operation.OperationHelper.releasingCallback;
@@ -227,27 +227,4 @@ private MongoException checkForDuplicateKeyError(final MongoCommandException e)
227227
return e;
228228
}
229229
}
230-
231-
/**
232-
* Convenience method to generate an index name from the set of fields it is over.
233-
*
234-
* @return a string representation of this index's fields
235-
*/
236-
private String generateIndexName(final BsonDocument index) {
237-
StringBuilder indexName = new StringBuilder();
238-
for (final String keyNames : index.keySet()) {
239-
if (indexName.length() != 0) {
240-
indexName.append('_');
241-
}
242-
indexName.append(keyNames).append('_');
243-
BsonValue ascOrDescValue = index.get(keyNames);
244-
if (ascOrDescValue instanceof BsonInt32) {
245-
indexName.append(((BsonInt32) ascOrDescValue).getValue());
246-
} else if (ascOrDescValue instanceof BsonString) {
247-
indexName.append(((BsonString) ascOrDescValue).getValue().replace(' ', '_'));
248-
}
249-
}
250-
return indexName.toString();
251-
}
252-
253230
}

driver-core/src/main/com/mongodb/operation/DropIndexOperation.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
import static com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol;
2929
import static com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocolAsync;
3030
import static com.mongodb.operation.CommandOperationHelper.isNamespaceError;
31+
import static com.mongodb.operation.IndexHelper.generateIndexName;
3132
import static com.mongodb.operation.OperationHelper.VoidTransformer;
3233

3334
/**
@@ -51,6 +52,17 @@ public DropIndexOperation(final MongoNamespace namespace, final String indexName
5152
this.indexName = notNull("indexName", indexName);
5253
}
5354

55+
/**
56+
* Construct a new instance.
57+
*
58+
* @param namespace the database and collection namespace for the operation.
59+
* @param keys the keys of the index to be dropped
60+
*/
61+
public DropIndexOperation(final MongoNamespace namespace, final BsonDocument keys) {
62+
this.namespace = notNull("namespace", namespace);
63+
this.indexName = generateIndexName(notNull("keys", keys));
64+
}
65+
5466
@Override
5567
public Void execute(final WriteBinding binding) {
5668
try {
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
* Copyright 2015 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.operation;
18+
19+
import org.bson.BsonDocument;
20+
import org.bson.BsonInt32;
21+
import org.bson.BsonString;
22+
import org.bson.BsonValue;
23+
24+
final class IndexHelper {
25+
26+
/**
27+
* Convenience method to generate an index name from the set of fields it is over.
28+
*
29+
* @return a string representation of this index's fields
30+
*/
31+
static String generateIndexName(final BsonDocument index) {
32+
StringBuilder indexName = new StringBuilder();
33+
for (final String keyNames : index.keySet()) {
34+
if (indexName.length() != 0) {
35+
indexName.append('_');
36+
}
37+
indexName.append(keyNames).append('_');
38+
BsonValue ascOrDescValue = index.get(keyNames);
39+
if (ascOrDescValue instanceof BsonInt32) {
40+
indexName.append(((BsonInt32) ascOrDescValue).getValue());
41+
} else if (ascOrDescValue instanceof BsonString) {
42+
indexName.append(((BsonString) ascOrDescValue).getValue().replace(' ', '_'));
43+
}
44+
}
45+
return indexName.toString();
46+
}
47+
48+
private IndexHelper() {
49+
}
50+
}

driver-core/src/test/functional/com/mongodb/operation/DropIndexesOperationSpecification.groovy

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ class DropIndexesOperationSpecification extends OperationFunctionalSpecification
7070
thrown(MongoException)
7171
}
7272

73-
def 'should drop existing index'() {
73+
def 'should drop existing index by name'() {
7474
given:
7575
collectionHelper.createIndex(new BsonDocument('theField', new BsonInt32(1)))
7676

@@ -83,6 +83,20 @@ class DropIndexesOperationSpecification extends OperationFunctionalSpecification
8383
indexes[0].name == '_id_'
8484
}
8585

86+
def 'should drop existing index by keys'() {
87+
def keys = new BsonDocument('theField', new BsonInt32(1))
88+
given:
89+
collectionHelper.createIndex(keys)
90+
91+
when:
92+
new DropIndexOperation(getNamespace(), keys).execute(getBinding())
93+
List<Document> indexes = getIndexes()
94+
95+
then:
96+
indexes.size() == 1
97+
indexes[0].name == '_id_'
98+
}
99+
86100
@Category(Async)
87101
def 'should drop existing index asynchronously'() {
88102
given:

driver/src/main/com/mongodb/MongoCollectionImpl.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,11 @@ public void dropIndex(final String indexName) {
437437
executor.execute(new DropIndexOperation(namespace, indexName));
438438
}
439439

440+
@Override
441+
public void dropIndex(final Bson keys) {
442+
executor.execute(new DropIndexOperation(namespace, keys.toBsonDocument(BsonDocument.class, codecRegistry)));
443+
}
444+
440445
@Override
441446
public void dropIndexes() {
442447
dropIndex("*");

driver/src/main/com/mongodb/client/MongoCollection.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -510,13 +510,21 @@ public interface MongoCollection<TDocument> {
510510
<TResult> ListIndexesIterable<TResult> listIndexes(Class<TResult> resultClass);
511511

512512
/**
513-
* Drops the given index.
513+
* Drops the index given its name.
514514
*
515515
* @param indexName the name of the index to remove
516516
* @mongodb.driver.manual reference/command/dropIndexes/ Drop indexes
517517
*/
518518
void dropIndex(String indexName);
519519

520+
/**
521+
* Drops the index given the keys used to create it.
522+
*
523+
* @param keys the keys of the index to remove
524+
* @mongodb.driver.manual reference/command/dropIndexes/ Drop indexes
525+
*/
526+
void dropIndex(Bson keys);
527+
520528
/**
521529
* Drop all the indexes on this collection, except for the default on _id.
522530
*

driver/src/test/acceptance/com/mongodb/acceptancetest/index/DropIndexAcceptanceTest.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,23 @@ public void shouldDropSingleNamedIndex() {
5454
assertThat("Should be one less index", collection.listIndexes().into(new ArrayList<Document>()).size(), is(1));
5555
}
5656

57+
@Test
58+
public void shouldDropSingleIndexByKeys() {
59+
// Given
60+
Document keys = new Document("field", 1);
61+
collection.createIndex(keys);
62+
63+
assertThat("Should be default index and new index on the database now",
64+
collection.listIndexes().into(new ArrayList<Document>()).size(),
65+
is(2));
66+
67+
// When
68+
collection.dropIndex(keys);
69+
70+
// Then
71+
assertThat("Should be one less index", collection.listIndexes().into(new ArrayList<Document>()).size(), is(1));
72+
}
73+
5774
@Test
5875
public void shouldDropAllIndexesForCollection() {
5976
// Given

0 commit comments

Comments
 (0)