2013-08-30 34 views
1

我想弄清楚如何在我的网站上进行高级搜索功能。我现在使用的代码效率不高,并且会创建一个非常昂贵的查询。什么是创造这样的一个很好的资源/例如:建立一个高级搜索栏

我的搜索控制器:

public ActionResult Index(string q = null, string authors = null, string category = null, decimal rating = 0, string published = null, int completed = 0, int page = 0) 
     { 
      List<string> categories = new List<string>(); 
      List<string> authorss = new List<string>(); 
      DateTime DateBy = new DateTime(); 
      DateTime.TryParse(published, out DateBy); 

      if(!string.IsNullOrEmpty(authors)) 
       authorss = authors.Split(',').ToList(); 
      if (!string.IsNullOrEmpty(category)) 
       categories = category.Split(',').ToList(); 


      IEnumerable<Comic> Comics = db.Comics.Where(i => i.Title.Contains(q)).Include(i => i.ComicRatings).Include(i => i.ComicAuthors).Include("ComicAuthors.User"); 

      if(authorss.Count() >= 1) 
      { 
       Comics = Comics.Where(i => i.ComicAuthors.Where(j => authorss.Contains(j.User.UserName)).GroupBy(j => j.Comic_Id).Where(j => j.Count() >= authorss.Count()).Any()); 
      } 

      if (categories.Count() >= 1) 
      { 
       Comics = Comics.Where(i => i.ComicCategories.Where(j => categories.Contains(j.Category.Name)).GroupBy(j => j.Comic_Id).Where(j => j.Count() >= categories.Count()).Any()); 
      } 

      if (rating != 0) 
      { 
       Comics = Comics.Where(i => i.ComicRatings.Where(j => j.Rating >= rating).Any()); 
      } 

      if (completed == 1) 
      { 
       Comics = Comics.Where(i => i.Completed == false); 
      } 
      else if (completed == 2) 
      { 
       Comics = Comics.Where(i => i.Completed == true); 
      } 

      if (!string.IsNullOrEmpty(published)) 
      { 
       Comics = Comics.Where(i => i.DatePublished >= DateBy); 
      } 

      if(page <= (Comics.Count()/20)) 
       page = 0; 

      Comics = Comics.Skip(page * 20).Take(20); 

      IEnumerable<LocalComicCategoriesModel> testing = helper.getCategories(); 
      ViewSearchModel post = new ViewSearchModel 
      { 
       Comic = Comics.ToList(), 
       Categories = testing 
      }; 

      return View(post); 
     } 

回答

1

如果你正在尝试做了很多文本搜索的我会看一看Lucene的.Net Lucene是一个非关系型全文搜索引擎,在很多地方都有使用。

我们花了很多年试图在sql和linq中进行文本搜索,然后将其全部扔掉并拥有完全专用的搜索系统。

+0

我要重申这个答案......即使你是不是想建“高级搜索“,我会使用Lucene。 –

+0

在实体中使用Lucene的好教程在哪里? –

+0

我不知道如何与实体和我的数据库合并。 –

0

我认为你的主要问题来自你正在检索太多漫画然后试图过滤它们的事实。作为第一步,我会尝试限制从数据库中检索漫画的数量。要做到这一点,您可以一次构建一个筛选器而不实际导致它执行(就像在调用结束时使用Any()一样)直到最后,或者使用谓词构建查询建设者。看看这两个问题,因为它们可以提供你所需要的:

Creating dynamic queries with entity framework

Building dynamic where clauses in LINQ to EF queries