Lucene. Net + MVC search function (I), lucene. netmvc

Source: Internet
Author: User
Tags createindex

Lucene. Net + MVC search function (I), lucene. netmvc
Preface

First, there are already many articles about Lucene. Net. I decided to write this article only to train the trainer. Although it seems useless to others, I did practice it manually. I personally think it makes sense. You can discover problems only when you are passionate about and dare to practice. Don't be afraid that you may write something wrong. If you have any questions, you can let more people see it. Of course, it is good to give comments and despise it ...... I also accept and give myself motivation to think.

I want to keep myself in this kind of programmer-> code mentality, people are all inert, once you play well...

Display Results

Enter topic

I believe that you are no stranger to LuceneNet, and there are many articles in the garden.

References:

Http://www.cnblogs.com/birdshover/category/152283.html

Http://www.cnblogs.com/psforever/archive/2011/10/06/2200019.html

 

The interface is manually created by an online tool. You can design the interface you want at will. However, the referenced css is not the css of Bootstrap. Pay attention to this.

Css style reference address: http://www.bootcss.com/p/layoutit/css/bootstrap-combined.min.css

Http://www.bootcss.com/p/layoutit/css/layoutit.css

Online tool address: http://www.bootcss.com/p/layoutit/

 

The database has about records, and a maximum of query results can be obtained each time. Normal people will not have read so much.

Core code method /// <summary> /// obtain the search list /// </summary> /// <param name = "keyword"> keyword </param> // /<param name = "pageSize"> </param> // <param name = "currentPage"> current page number </param> // <param name = "count"> </param> /// <param name = "pageCount"> </param> /// <param name = "isLike"> enable fuzzy search </param>/ // <returns> </returns> public static List <StoreInfo> GetSearchList (string keyword, int pageSize, int currentPage, out int co Unt, out int pageCount, bool isLike = false) {string keywords = keyword; // you can specify string strIndexPath = INDEX_STORE_PATH to indicate the keyword you entered; list <StoreInfo> storeList = new List <StoreInfo> (); StoreInfo modelstore; pageCount = 0; count = 0; IndexSearcher search = null; try {search = new IndexSearcher (FSDirectory. open (new System. IO. directoryInfo (strIndexPath), true);} catch (Exception) {return null ;} Keyword = GetKeyWordsSplitBySpace (keyword, new PanGuTokenizer (); QueryParser titleQueryParser = new QueryParser (Lucene. net. util. version. required e_29, "body", new PanGuAnalyzer (true); Query titleQuery = titleQueryParser. parse (keyword); Query PrefixQuery_title = null; Query PrefixQuery_body = null; Query FuzzyQuery_Title = null; Query FuzzyQuery_body = null; Query WildcardQuery_title = null; Query W IldcardQuery_body = null; if (isLike) {// start with something, enter "ja" to search for PrefixQuery_title = new PrefixQuery (new Term ("title", keywords) with java and javascript results )); prefixQuery_body = new PrefixQuery (new Term ("body", keywords); // perform fuzzy match directly. Suppose you want to search for words similar to 'wuzza, you may get 'fuzzy 'and 'wuyun '. FuzzyQuery_Title = new FuzzyQuery (new Term ("title", keywords); FuzzyQuery_body = new FuzzyQuery (new Term ("body", keywords )); // search WildcardQuery_title = new WildcardQuery (new Term ("title", keywords); WildcardQuery_body = new WildcardQuery (new Term ("body", keywords ));} // MultiFieldQueryParser BooleanQuery bq = new BooleanQuery (); bq. add (titleQuery, BooleanClause. occur. shocould); // indicates that the condition relation is "or", BooleanClause. occur. MUST indicates "and", BooleanClause. occur. MUST_NOT indicates "not" if (isLike) {bq. add (PrefixQuery_title, BooleanClause. occur. shocould); bq. add (PrefixQuery_body, BooleanClause. occur. shocould); bq. add (FuzzyQuery_Title, BooleanClause. occur. shocould); bq. add (FuzzyQuery_body, BooleanClause. occur. shocould); bq. add (WildcardQuery_title, BooleanClause. occur. shocould); bq. add (WildcardQuery_body, BooleanClause. occur. shocould);} // create a result collector (the maximum number of collection results is 1000 pages) TopScoreDocCollector collector = TopScoreDocCollector. create (pageSize * 1000, true); search. search (bq, null, collector); TopDocs topDoc = collector. topDocs (0, collector. getTotalHits (); // if (topDoc. totalHits> pageSize * 1000) count = pageSize * 1000; else count = topDoc. totalHits; int I = (currentPage-1) * pageSize; # region Lucene. net. documents. document docs; PanGu. highLight. highlighter highlighter; PanGu. highLight. simpleHTMLFormatter simpleHTMLFormatter; while (I <count & storeList. count <pageSize) {modelstore = new StoreInfo (); docs = search.doc(topdoc.scoredocs? I =.doc); try {string strTitle = docs. get ("title"); string strContent = docs. get ("body"); modelstore. store_ID = Convert. toInt32 (docs. get ("id"); // set simpleHTMLFormatter = new PanGu. highLight. simpleHTMLFormatter ("<span style = \" color: red; \ ">", "</span>"); highlighter = new PanGu. highLight. highlighter (simpleHTMLFormatter, new PanGu. segment (); highlighter. fragmentSize = 200; // string GetBestFragment (keywords, content) the method is used to highlight the keywords in the content according to the format constructed by SimpleHTMLFormatter. // However, if the content does not contain keywords, a null value is returned. Therefore, modelstore must be determined as follows. description = highlighter. getBestFragment (keywords, strContent); if (string. isNullOrEmpty (modelstore. description) {modelstore. description = strContent;} modelstore. store_Name = highlighter. getBestFragment (keywords, strTitle); if (string. isNullOrEmpty (modelstore. store_Name) {modelstore. store_Name = strTitle;} catch (Exception e) {continue;} finally {storeList. add (modelstore); I ++ ;}# endregion search. close (); pageCount = Convert. toInt32 (Math. ceiling (double) collector. getTotalHits ()/pageSize); return storeList ;}View Code controller public ActionResult Index (string id = "", string kw = "", string isLike = "0", int pageIndex = 1) {string strKeyWorld = HttpDecode (id. length = 0? Kw: id); int pageSize = 10; int intCount = 0; int intPageCount = 0; bool _ boolisLike = isLike = "1 "? True: false; List <StoreInfo> StoreInfoList = null; Stopwatch watch = new Stopwatch (); watch. start (); // call the method to Start timing if (strKeyWorld. length> 0) {StoreInfoList = incluenetutils. getSearchList (strKeyWorld, pageSize, pageIndex, out intCount, out intPageCount, _ boolisLike);} watch. stop (); // call method timing to end double time = watch. elapsed. totalSeconds; // total time spent ViewBag. time = time; ViewBag. kw = strKeyWorld; ViewBag. count = intCount; ViewBag. pageIndex = pageIndex; ViewBag. pageSize = pageSize; ViewBag. intPageCount = intPageCount; ViewBag. _ boolisLike = _ boolisLike; return View (StoreInfoList );}View CodeView View

Note: ShowPageBarMvc is a page number. When using it in the page, you must reference the namespace or add webConfig.

@ Using System. web. optimization; @ using LX. EFOPT. web. main. commonUtils; @ using PagedList. mvc; @ model List <LX. EFOPT. web. main. models. storeInfo >@{ Layout = "/Views/Shared/_ LayoutLucene. cshtml ";}< script src = "~ /Js/jquery. ds. js "> </script> <div class =" container-fluid "> <div class =" row-fluid "> <div class =" span12 "> <form class =" form-search "action ="/enet/index/"onsubmit =" return _ search. checkInput (); "> <input class =" input-medium search-query "id =" inputKw "name =" kw "value =" @ ViewBag. kw "type =" text "/> <button id =" btn_search "type =" submit "class =" btn "> Search </button> & nbsp; <input type = "checkbox" @ (ViewBag. _ bool IsLike? "Checked = checked ":"") name = "isLike" id = "isLike" value = "1"/> <label for = "isLike"> enable fuzzy search </label> & nbsp; & nbsp; <button id = "btn_createIndex1" type = "button" class = "btn"> index creation-method 1 </button> <button id = "btn_createIndex2" type = "button" class = "btn"> Create an index-method 2 </button> </form> <div id = "ajaxData" style = "width: 80% "> @ {if (Model! = Null) {<div style = "margin-top: 20px;"> <p> Get approx. @ ViewBag. count results, @ ViewBag. time seconds </p> </div> foreach (var item in Model) {<div style = "margin-top: 20px;">  

In the next article, we will continue to add and delete indexes to and synchronize with the database.

The source code is just a project I tested at the company. It is quite complicated and cannot be downloaded in full. But I will upload the code to git or a network disk.

Thank you.

Address: http://www.cnblogs.com/lxsweat/p/4386420.html

 

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.