我有一个代码可以按名称在 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];
}
相关分类