public class Book { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid Id { get; set; } [MaxLength(500)] [Display(Name = "标题")] public string Title { get; set; } [MaxLength(5000)] [Display(Name = "前言")] public string Foreword { get; set; } [Display(Name = "总页数")] public int Pages { get; set; } [Display(Name = "作者")] public string Author { get; set; } }
public class AppContext:DbContext { public AppContext() { } public DbSet<Book> Books { get; set; } }
ViewModels的相关:
public class SearchViewModel { public string Query { get; set; } public IEnumerable<IHit<Book>> Results { get; set; } public IDictionary<string, Suggest[]> Suggestions { get; set; } public long Elapsed { get; set; } }
接下来就HomeController.cs和BooksController.cs的代码:
public class HomeController : Controller { private SearchService _searchService; public HomeController() { _searchService = new SearchService(); } public ActionResult Index() { return View(); } public ActionResult Search(string query, int page = 0, int pageSize = 10) { var result = _searchService.Find(query, page, pageSize); var suggestion = _searchService.FindPhraseSuggestion(query, 0, 3); var viewModel = new SearchViewModel { Query = query, Results = result.Item1,Elapsed = result.Item2, Suggestions = suggestion }; return View("Index", viewModel); } }
public class BooksController : Controller { private AppContext db = new AppContext(); public ActionResult Index() { return View(db.Books.ToList()); } public ActionResult Details(Guid? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Book book = db.Books.Find(id); if (book == null) { return HttpNotFound(); } return View(book); } public ActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include="Id,Title,Foreword,Pages,Author")] Book book) { if (ModelState.IsValid) { book.Id = Guid.NewGuid(); db.Books.Add(book); db.SaveChanges(); //添加书 Elasticsearch.Elasticsearch.Client.Index<Book>(book); return RedirectToAction("Index"); } return View(book); } public ActionResult Edit(Guid? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Book book = db.Books.Find(id); if (book == null) { return HttpNotFound(); } return View(book); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include="Id,Title,Foreword,Pages,Author")] Book book) { if (ModelState.IsValid) { db.Entry(book).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(book); } public ActionResult Delete(Guid? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Book book = db.Books.Find(id); if (book == null) { return HttpNotFound(); } return View(book); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(Guid id) { Book book = db.Books.Find(id); db.Books.Remove(book); db.SaveChanges(); return RedirectToAction("Index"); } public JsonResult Reindex() { foreach (var book in db.Books) { //Indexing book Elasticsearch.Elasticsearch.Client.Index<Book>(book); } return Json("OK",JsonRequestBehavior.AllowGet); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } }
Elasticsearch辅助类:
首先是Elasticsearch.cs
public class Elasticsearch { private static ElasticClient _client; public static ElasticClient Client { get { if (_client == null) { //连接配置 var setting = new ConnectionSettings(ElasticsearchConfiguration.Connection,ElasticsearchConfiguration.DefaultIndex); _client = new ElasticClient(setting); } return _client; } } }
ElasticsearchConfiguration.cs类
public static class ElasticsearchConfiguration { public static string Host { get { return "http://localhost"; } } public static long Port { get { return 9200; } } public static Uri Connection { get { return new Uri(string.Format("{0}:{1}", Host, Port)); } } public static string DefaultIndex { get { return "library"; } } }
SearchService.cs代码:
public class SearchService { public double MinScore { get {return 0.0005; }} //高亮标记前缀 public string PreHighlightTag { get { return @"<strong>"; } } //高亮标记后缀 public string PostHighlightTag { get { return @"</strong>"; } } public Tuple< IEnumerable<IHit<Book>>,long> Find(string query, int page = 0, int pageSize = 10) { var result = Elasticsearch.Elasticsearch.Client.Search<Book>(s => s .From(page * pageSize) .Size(pageSize) .MinScore(MinScore) .Highlight(h => h .PreTags(PreHighlightTag) .PostTags(PostHighlightTag) .OnFields( f => f.OnField(b => b.Foreword), f => f.OnField(b => b.Title) )) .Query(q => q.QueryString(qs => qs.Query(query).UseDisMax()))); return new Tuple<IEnumerable<IHit<Book>>, long>(result.Hits,result.ElapsedMilliseconds); } //查找短语建议 public IDictionary<string, Suggest[]> FindPhraseSuggestion(string phrase, int page = 0, int pageSize = 5) { var result = Elasticsearch.Elasticsearch.Client.Search<Book>(s => s .From(page*pageSize) .Size(pageSize) .SuggestPhrase("did-you-mean", ps => ps .Text(phrase) .OnField(f => f.Foreword)) .Query(q => q.MatchAll())); return result.Suggest; } public IEnumerable<IHit<Book>> FindAll() { var result = Elasticsearch.Elasticsearch.Client.Search<Book>(s => s.AllIndices()); return result.Hits; } }
Views视图
Books文件夹下:
Index.cshtml: