Elasticsearch. Net tutorial MVC4 Library Management System (2 ),

Source: Internet
Author: User
Tags actionlink

Elasticsearch. Net tutorial MVC4 Library Management System (2 ),

This article provides an example of creating an MVC4 Library Management System for your reference. The details are as follows:

First, the project structure:

Code related to the Model layerAs follows:
The Book. cs code is as follows:

Public class Book {[Key] [DatabaseGenerated (DatabaseGeneratedOption. identity)] public Guid Id {get; set;} [MaxLength (500)] [Display (Name = "Title")] public string Title {get; set ;} [MaxLength (5000)] [Display (Name = "Preface")] public string Foreword {get; set;} [Display (Name = "total page")] public int Pages {get; set;} [Display (Name = "Author")] 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; }   } 

The following describes the codes of HomeController. cs and 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 = 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) {if (ModelState. isValid) {book. id = Guid. N EwGuid (); db. books. add (book); db. saveChanges (); // Add 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 = 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) {if (ModelState. isValid) {db. entry (book ). state = EntityState. modified; db. saveChanges (); ret Urn RedirectToAction ("Index");} return View (book);} public ActionResult Delete (Guid? Id) {if (id = null) {return new HttpStatusCodeResult (HttpStatusCode. badRequest);} 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 helper class:
First, Elasticsearch. cs

Public class Elasticsearch {private static ElasticClient _ client; public static ElasticClient Client {get {if (_ client = null) {// connection configuration var setting = new ConnectionSettings (ElasticsearchConfiguration. connection, ElasticsearchConfiguration. defaultIndex); _ client = new ElasticClient (setting);} return _ client ;}}}

ElasticsearchConfiguration. cs class

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 code:

Public class SearchService {public double MinScore {get {return 0.0005 ;}// highlight the prefix public string PreHighlightTag {get {return @ "<strong> ";}} // highlight the suffix 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
Under the Books Folder:
Index. cshtml:

@ Model IEnumerable <Library. Web. Models. Book> @ {ViewBag. Title = "Index"; Layout = "~ /Views/Shared/_ Layout. cshtml ";}< h2> Index 

Edit. cshtml:

@ Model Library. Web. Models. Book @ {ViewBag. Title = "Edit"; Layout = "~ /Views/Shared/_ Layout. cshtml ";}< h2> Edit 

Details. cshtml:

@ Model Library. Web. Models. Book @ {ViewBag. Title = "Details"; Layout = "~ /Views/Shared/_ Layout. cshtml ";} 

Delete. cshtml:

@ Model Library. Web. Models. Book @ {ViewBag. Title = "Delete"; Layout = "~ /Views/Shared/_ Layout. cshtml ";}< h2> Delete 

Create. cshtml:

@ Model Library. Web. Models. Book @ {ViewBag. Title = "Create"; Layout = "~ /Views/Shared/_ Layout. cshtml ";}< h2> Create 

Home-> Index. cshtml

@ Model Library. web. viewModels. searchViewModel @ {ViewBag. title = "Elasticsearch ";} <div class = "jumbotron"> 

_ Layout. cshtml

<! DOCTYPE html> 

Result:


List page


Create page:


Search result page:


The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.