【发布时间】:2021-03-15 08:01:54
【问题描述】:
我需要什么:
考虑 700 万 个此类对象的列表:
public class Item
{
[Key]
public int Id { get; set; }
public List<Person> People { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Tags { get; set; }
public List<Category> Categories { get; set; }
public float Rating { get; set; }
public int Yar { get; set; }
public long Visits { get; set; }
}
public class Person
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class Category
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
我希望能够对所有记录进行实时搜索(“StartsWith”或“Contains”)。通过“实时搜索”,我的意思是当用户键入结果时应该建议(如谷歌)。我希望能够在多个字段或它们的组合上运行。
到目前为止我尝试了什么:
我尝试使用 Linq 直接查询数据库。像这样:
await db.Items.Include(i => i.People).Where(i => i.Name.Contains(query) || i.People.Any(p => p.Name.Contains(query))).ToListAsync();
但是太慢了。然后我尝试将它们缓存在内存中。它大约有 8GB 的 RAM,但除了网站启动时非常缓慢的缓存过程和硬维护之外,查询仍然很慢。
缓存是指在网站开始时将这些表上的所有内容加载到内存中,并使用内存数据库上的 Linq 进行查询。
我认为需要的是某种基于树的文档索引。但是,我不知道有什么好的库/方法可以做到这一点。
我应该使用全文搜索引擎吗?我看到网站一直在这样做。
PS:
我使用 MongoDb 来存储数据。以前我有 SQL Server 数据库上的数据,但项目过于复杂,使用非关系数据库大大提高了性能。
【问题讨论】:
-
我强烈建议您为此目的使用 ElasticSearch 或 Azure Search。
-
Trie 可以很好地解决这类问题:en.wikipedia.org/wiki/Trie
-
Mongodb 现在提供 Atlas Search,聚合管道中完全托管的 Lucene 搜索。 docs.atlas.mongodb.com/atlas-search
标签: c# asp.net linq search full-text-search