[英]Program not scaling up with MongoDB
我有一個按名稱搜索MongoDB中人員的代碼。 我的代碼的問題在於它沒有按比例擴展,我嘗試使用40個線程來運行此代碼,但是當我在數據庫中弄清響應時,我不得不關閉它,因為它占用了100%的CPU。 正在搜索的所有三個字段都在MongoDB中建立了索引。 有沒有辦法改善查詢? 我需要運行500萬個名稱,我的數據庫有2億多人。
public Person searchPerson(string name)
{
string MongoUser = "MONGO_USERNAME";
string MongoPass = "MONGO_PASSWORD";
string MongoURL = "MONGO_URL";
string MongoDB = "MONGO_DB";
MongoClient _client = new MongoClient("mongodb://" + MongoUser + ":" + MongoPass + "@" + MongoURL);
IMongoCollection<BazingaPerson> myCollection = _client.GetDatabase (MongoDB).GetCollection<Person> ("COLLECTION_NAME");
List<Person> peopleList = myCollection.AsQueryable<Person>().Where(e => e.Name == name).ToList<Person>();
// both functions below only transform string like replace, substring or splits . They dont query in a DB or make web requests
string nameInitials = getInitials(name);
string phoneticName = getPhoneticName(name);
if(peopleList.Count() == 0) peopleList = myCollection.AsQueryable<Person>().Where(e => e.StandardName.Equals (phoneticName)).ToList<Person>();
if(peopleList.Count() == 0) peopleList = myCollection.AsQueryable<Person>().Where(e => e.Initials.Equals (nameInitials)).ToList<Person>();
if(peopleList.Count() == 0) return null;
return peopleList[0];
}
我需要運行500萬個名稱,我的數據庫有2億多人。
將您的500萬條記錄插入臨時表中,然后運行單個查詢以獲取結果集。 讓數據庫想知道如何最好地解決這個問題。 這是他們的工作,大多數人都擅長。
只需將其與實際的人員名單進行比較即可。 您想將此列表分給一個進行查找的人,然后讓他不受干擾地進行處理,直到他完成為止。 您不希望做的是再雇用40個人 ,每隔幾秒鍾就用一個名字敲開這個窮人的門,告訴他現在要查那個名字。
是MongoDB進程最多使用100%CPU還是您的應用程序?
如果是應用程序,則有一些提示:
不要為每個查詢創建新的MongoDB客戶端。 將它們保留在(線程本地)實例變量中。
到達網絡的方法(例如您的searchPerson
方法)最好應異步實現。 ```public async Task searchPerson(string name){// ...
List<Person> peopleList = await Task.Run(() => myCollection.AsQueryable<Person>().Where(e => e.Name == name).ToList<Person>()); // ...
}```
(也許您可以跳過Task.Run並使用異步版本的MongoDB客戶端)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.