Elasticsearch.Net如何实现MVC4图书管理系统-创新互联
这篇文章主要介绍了Elasticsearch.Net如何实现MVC4图书管理系统,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
创新互联是一家专注于做网站、成都网站制作与策划设计,柘城网站建设哪家好?创新互联做网站,专注于网站建设10多年,网设计领域的专业建站公司;建站业务涵盖:柘城等地区。柘城做网站价格咨询:18980820575首先项目结构图:
Model层的相关代码如下:
Book.cs代码如下:
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 DbSetBooks { get; set; } }
ViewModels的相关:
public class SearchViewModel { public string Query { get; set; } public IEnumerable> Results { get; set; } public IDictionary 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); 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); } 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 @""; } } //高亮标记后缀 public string PostHighlightTag { get { return @""; } } public Tuple< IEnumerable>,long> Find(string query, int page = 0, int pageSize = 10) { var result = Elasticsearch.Elasticsearch.Client.Search (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 >, long>(result.Hits,result.ElapsedMilliseconds); } //查找短语建议 public IDictionary FindPhraseSuggestion(string phrase, int page = 0, int pageSize = 5) { var result = Elasticsearch.Elasticsearch.Client.Search (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 > FindAll() { var result = Elasticsearch.Elasticsearch.Client.Search (s => s.AllIndices()); return result.Hits; } }
Views视图
Books文件夹下:
Index.cshtml:
@model IEnumerable@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } Index
@Html.ActionLink("创建新书", "Create")
@foreach (var item in Model) { @Html.DisplayNameFor(model => model.Title) @Html.DisplayNameFor(model => model.Foreword) @Html.DisplayNameFor(model => model.Pages) @Html.DisplayNameFor(model => model.Author) } @Html.DisplayFor(modelItem => item.Title) @Html.DisplayFor(modelItem => item.Foreword) @Html.DisplayFor(modelItem => item.Pages) @Html.DisplayFor(modelItem => item.Author) @Html.ActionLink("编辑", "Edit", new { id=item.Id }) | @Html.ActionLink("详细", "Details", new { id=item.Id }) | @Html.ActionLink("删除", "Delete", new { id=item.Id })
Edit.cshtml:
@model Library.Web.Models.Book @{ ViewBag.Title = "Edit"; Layout = "~/Views/Shared/_Layout.cshtml"; }Edit
@using (Html.BeginForm()) { @Html.AntiForgeryToken()}Book
@Html.ValidationSummary(true) @Html.HiddenFor(model => model.Id)@Html.LabelFor(model => model.Title, new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title)@Html.LabelFor(model => model.Foreword, new { @class = "control-label col-md-2" })@Html.TextAreaFor(model => model.Foreword) @Html.ValidationMessageFor(model => model.Foreword)@Html.LabelFor(model => model.Pages, new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Pages) @Html.ValidationMessageFor(model => model.Pages)@Html.LabelFor(model => model.Author, new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Author) @Html.ValidationMessageFor(model => model.Author)@Html.ActionLink("返回列表", "Index")@section Scripts { @Scripts.Render("~/bundles/jqueryval") }
Details.cshtml:
@model Library.Web.Models.Book @{ ViewBag.Title = "Details"; Layout = "~/Views/Shared/_Layout.cshtml"; }Details
Book
- @Html.DisplayNameFor(model => model.Title)
- @Html.DisplayFor(model => model.Title)
- @Html.DisplayNameFor(model => model.Foreword)
- @Html.DisplayFor(model => model.Foreword)
- @Html.DisplayNameFor(model => model.Pages)
- @Html.DisplayFor(model => model.Pages)
- @Html.DisplayNameFor(model => model.Author)
- @Html.DisplayFor(model => model.Author)
@Html.ActionLink("编辑", "Edit", new { id = Model.Id }) | @Html.ActionLink("返回列表", "Index")
Delete.cshtml:
@model Library.Web.Models.Book @{ ViewBag.Title = "Delete"; Layout = "~/Views/Shared/_Layout.cshtml"; }Delete
Are you sure you want to delete this?
Book
@using (Html.BeginForm()) { @Html.AntiForgeryToken()
- @Html.DisplayNameFor(model => model.Title)
- @Html.DisplayFor(model => model.Title)
- @Html.DisplayNameFor(model => model.Foreword)
- @Html.DisplayFor(model => model.Foreword)
- @Html.DisplayNameFor(model => model.Pages)
- @Html.DisplayFor(model => model.Pages)
- @Html.DisplayNameFor(model => model.Author)
- @Html.DisplayFor(model => model.Author)
| @Html.ActionLink("返回列表", "Index")}
Create.cshtml:
@model Library.Web.Models.Book @{ ViewBag.Title = "Create"; Layout = "~/Views/Shared/_Layout.cshtml"; }创建
@using (Html.BeginForm()) { @Html.AntiForgeryToken()}Book
@Html.ValidationSummary(true)@Html.LabelFor(model => model.Title, new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title)@Html.LabelFor(model => model.Foreword, new { @class = "control-label col-md-2" })@Html.TextAreaFor(model => model.Foreword) @Html.ValidationMessageFor(model => model.Foreword)@Html.LabelFor(model => model.Pages, new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Pages) @Html.ValidationMessageFor(model => model.Pages)@Html.LabelFor(model => model.Author, new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Author) @Html.ValidationMessageFor(model => model.Author)@Html.ActionLink("回到列表", "Index")@section Scripts { @Scripts.Render("~/bundles/jqueryval") }
Home->Index.cshtml
@model Library.Web.ViewModels.SearchViewModel @{ ViewBag.Title = "Elasticsearch"; } @if (Model == null) { return; }@if (Model.Suggestions.Any(x => x.Key == "did-you-mean")) { 你的意思是: foreach (var suggestions in Model.Suggestions["did-you-mean"]) { var count = 0; foreach (var suggestion in suggestions.Options) { @suggestion.Text count++; } if (count == 0) { 没有建议! } } }Results for: @Model.Query
@if (Model != null) {
文档的分数(排名相关度) | Title | Content | Author |
---|---|---|---|
@result.Score | @if (result.Highlights != null && result.Highlights.Any(x => x.Key == "title")) { var hl = result.Highlights.FirstOrDefault(x => x.Key == "title"); foreach (var h in hl.Value.Highlights) { WriteLiteral(h); } } else { WriteLiteral(result.Source.Title); } | @if (result.Highlights != null && result.Highlights.Any(x => x.Key == "foreword")) { var hl = result.Highlights.FirstOrDefault(x => x.Key == "foreword"); foreach (var h in hl.Value.Highlights) { WriteLiteral(h + "..."); } } | @result.Source.Author |
没有结果发现:( |
@Model.Results.Count()搜索结果用了 @Model.Elapsed 毫秒
}_Layout.cshtml
@ViewBag.Title @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr")@Html.ActionLink("Elasticsearch MVC示例", "Index", "Home", null, new { @class = "navbar-brand" })@using (Html.BeginForm("Search", "Home", FormMethod.Get,new {@class = "navbar-form navbar-left"})) {
- @Html.ActionLink("Home", "Index", "Home")
- @Html.ActionLink("Books", "Index", "Books")
}@RenderBody()@Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false)
结果如图:
列表页
创建页:
搜索结果页:
感谢你能够认真阅读完这篇文章,希望小编分享的“Elasticsearch.Net如何实现MVC4图书管理系统”这篇文章对大家有帮助,同时也希望大家多多支持创新互联网站建设公司,,关注创新互联行业资讯频道,更多相关知识等着你来学习!
新闻名称:Elasticsearch.Net如何实现MVC4图书管理系统-创新互联
链接URL:http://azwzsj.com/article/jjsoe.html