인덱스가 사용 중인지 확인하는 방법
나는 많은 데이터베이스, 컬렉션 및 색인이 있는 mongodb 복제본 세트를 가지고 있습니다.
우리는 리팩터와 최적화를 많이 했고, 물론 소비자들로부터 "창의적인 질문"을 많이 받았습니다.
사용하지 않은 인덱스를 정리하고 싶습니다.공간을 좀 절약하고 싶을 뿐입니다.
인덱스가 사용되고 있는지 확인하려면 어떻게 해야 합니까?인덱스별로 인덱스를 확인하고 사용하지 않은 것은 드롭할 여유가 있습니다.
가능한 모든 쿼리에서 "설명"을 실행하는 것은 옵션이 아닙니다 :)
편집: 수락된 답변을 기반으로 한 솔루션
스크립트가 도청되었습니다.저는 자바스크립트 전문가는 아니지만 수정된 스크립트를 넣었습니다.누군가에게 도움이 되기를 바랍니다.
DB.prototype.indexStats = function() {
var queries = [];
var collections = db.getCollectionNames();
var findQuery = function(q) {
for(entryIdx in queries) {
if(q == queries[entryIdx].query) {
return entryIdx;
}
}
return -1;
}
for(cIdx in collections) {
var cName = collections[cIdx];
var nsName = db.getName()+"."+cName;
if(cName.indexOf("system") == -1) {
var i = 1;
var count = db.system.profile.count({ns:nsName});
print('scanning profile {ns:"'+nsName+'"} with '+count+' records... this could take a while...');
db.system.profile.find({ns:nsName}).addOption(16).batchSize(10000).forEach(function(profileDoc) {
if(profileDoc.query && !profileDoc.query["$explain"]) {
var qIdx = findQuery(profileDoc.query);
if(qIdx == -1 && profileDoc.query["query"] ) {
var size = queries.push({query:profileDoc.query, count:1, index:""});
var explain = db[cName].find(queries[size-1].query).explain();
if(profileDoc.query && profileDoc.query["query"]) {
queries[size-1].sort = profileDoc.query["orderby"];
if(queries[size-1].sort) {
explain = db[cName].find(queries[size-1].query.query).sort(queries[size-1].sort).explain();
}
}
queries[size-1].cursor = explain.cursor;
queries[size-1].millis = explain.millis;
queries[size-1].nscanned = explain.nscanned;
queries[size-1].n = explain.n;
queries[size-1].scanAndOrder = explain.scanAndOrder ? true : false;
if(explain.cursor && explain.cursor != "BasicCursor") {
queries[size-1].index = explain.cursor.split(" ")[1];
} else {
print('warning, no index for query {ns:"'+nsName+'"}: ');
printjson(profileDoc.query);
print('... millis: ' + queries[size-1].millis);
print('... nscanned/n: ' + queries[size-1].nscanned + '/' + queries[size-1].n);
print('... scanAndOrder: ' + queries[size-1].scanAndOrder);
}
} else if ( qIdx != -1 ) {
queries[qIdx].count++;
}
}
});
}
}
for(cIdx in collections) {
var cName = collections[cIdx];
if(cName.indexOf("system") == -1) {
print('checking for unused indexes in: ' + cName);
for(iIdx in db[cName].getIndexes()) {
var iName = db[cName].getIndexes()[iIdx].name;
if(iName.indexOf("system") == -1) {
var stats = db[cName].stats();
var found = false;
for(qIdx in queries) {
if(queries[qIdx].index == iName) {
found = true;
break;
}
}
if(!found) {
print('this index is not being used: ');
printjson(iName);
}
}
}
}
}
}
이에 대한 가장 간단한 솔루션은 MongoDB 3.2에 추가된 내장 $indexStats 집계 단계를 사용하는 것입니다.
Mongo 콘솔 사용:
db.collection.aggregate([ { $indexStats: { } } ])
PyMongo 사용:
from pymongo import MongoClient
collection = MongoClient()[db_name][collection_name]
index_stats = collection.aggregate([{'$indexStats':{}}])
for index_info in index_stats:
print index_info
Github에는 다음과 같은 멋진 스크립트가 있습니다.
https://github.com/wfreeman/indexalizer
기본적으로 데이터베이스에 대한 프로파일링을 설정한 다음 프로파일러가 수집한 데이터를 사용하여 설명() 호출을 수행합니다.그런 다음 사용되지 않는 인덱스와 인덱스를 사용하지 않는 쿼리를 모두 알려줍니다.꽤 매끈해요.
mongoDB 데이터베이스 프로파일링에 대해 자세히 알아보기:
http://docs.mongodb.org/manual/reference/database-profiler/
언급URL : https://stackoverflow.com/questions/24535439/how-do-i-check-if-an-index-is-being-used
'programing' 카테고리의 다른 글
VBA : BOM 없이 UTF-8로 파일 저장 (0) | 2023.07.03 |
---|---|
Spring Data REST에서 JSON 응답으로 ID를 반환합니다. (0) | 2023.07.03 |
Maria docker passWordCharacterEncoding 문제 (0) | 2023.07.03 |
VBA에 주석 블록 구문이 포함되어 있습니까? (0) | 2023.07.03 |
패키지를 로드할 때 메시지 사용 안 함 (0) | 2023.07.03 |