2013-08-30 35 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