Skip to content
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

SERVER-84667:index check, avoid create duplicate btree indexes, Avoid affecting performance #1588

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
36 changes: 34 additions & 2 deletions src/mongo/db/index/index_descriptor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,41 @@ IndexDescriptor::Comparison IndexDescriptor::compareIndexOptions(
const IndexCatalogEntry* existingIndex) const {
auto existingIndexDesc = existingIndex->descriptor();

//Index check, avoid creating duplicate indexes.
//For example:
// Add two indexes: db.collection.createIndex({a:1}) and db.collection.createIndex({a:11})
// The two indexes are actually the same, One of them is a useless index
auto canonizeIndexKeyPattern = [this](const BSONObj& indexKeyPattern) {
if (getIndexType() != INDEX_BTREE) {
return indexKeyPattern;
}

//Hidden index is not restricted
if (hidden() == true) {
return indexKeyPattern;
}

BSONObjBuilder build;
BSONObjIterator kpIt(indexKeyPattern);
while (kpIt.more()) {
BSONElement elt = kpIt.next();

// The canonical check as to whether a key pattern element is "ascending" or "descending" is
// (elt.number() >= 0). This is defined by the Ordering class.
invariant(elt.isNumber());
int sortOrder = (elt.number() >= 0) ? 1 : -1;
build.append(elt.fieldName(), sortOrder);
}

return build.obj();
};

BSONObj newIndexKeyPattern = canonizeIndexKeyPattern(keyPattern());
BSONObj existingIndexKeyPattern = canonizeIndexKeyPattern(existingIndexDesc->keyPattern());

// We first check whether the key pattern is identical for both indexes.
if (SimpleBSONObjComparator::kInstance.evaluate(keyPattern() !=
existingIndexDesc->keyPattern())) {
if (SimpleBSONObjComparator::kInstance.evaluate(newIndexKeyPattern !=
existingIndexKeyPattern)) {
return Comparison::kDifferent;
}

Expand Down