<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12
      Fork me on GitHub

      火力全開——仿造Baidu簡單實現基于Lucene.net的全文檢索的功能

      Lucene.Net

      Lucene.net是Lucene的.net移植版本,是一個開源的全文檢索引擎開發包,即它不是一個完整的全文檢索引擎,而是一個全文檢索引擎的架構,是一個Library.你也可以把它理解為一個將索引,搜索功能封裝的很好的一套簡單易用的API(提供了完整的查詢引擎和索引引擎)。利用這套API你可以做很多有關搜索的事情,而且很方便.。開發人員可以基于Lucene.net實現全文檢索的功能。

      注意:Lucene.Net只能對文本信息進行檢索。如果不是文本信息,要轉換為文本信息,比如要檢索Excel文件,就要用NPOI把Excel讀取成字符串,然后把字符串扔給Lucene.Net。Lucene.Net會把扔給它的文本切詞保存,加快檢索速度。

      更多概念性的知識可以參考這篇博文:http://blog.csdn.net/xiucool/archive/2008/11/28/3397182.aspx

      這個小Demo樣例展示:

      ok,接下來就細細詳解下士怎樣一步一步實現這個效果的。

      Lucene.Net 核心——分詞算法(Analyzer)

      學習Lucune.Net,分詞是核心。當然最理想狀態下是能自己擴展分詞,但這要很高的算法要求。Lucene.Net中不同的分詞算法就是不同的類。所有分詞算法類都從Analyzer類繼承,不同的分詞算法有不同的優缺點。

      • 內置的StandardAnalyzer是將英文按照空格、標點符號等進行分詞,將中文按照單個字進行分詞,一個漢字算一個詞
                  Analyzer analyzer = new StandardAnalyzer();
                  TokenStream tokenStream = analyzer.TokenStream("",new StringReader("Hello Lucene.Net,我1愛1你China"));
                  Lucene.Net.Analysis.Token token = null;
                  while ((token = tokenStream.Next()) != null)
                  {
                      Console.WriteLine(token.TermText());
                  }

      分詞后結果:

      • 二元分詞算法,每兩個漢字算一個單詞,“我愛你China”會分詞為“我愛 愛你 china”,點擊查看二元分詞算法CJKAnalyzer。
                  Analyzer analyzer = new CJKAnalyzer();
                  TokenStream tokenStream = analyzer.TokenStream("", new StringReader("我愛你中國China中華人名共和國"));
                  Lucene.Net.Analysis.Token token = null;
                  while ((token = tokenStream.Next()) != null)
                  {
                      Response.Write(token.TermText()+"<br/>");
                  }

      這時,你肯定在想,上面沒有一個好用的,二元分詞算法亂槍打鳥,很想自己擴展Analyzer,但并不是算法上的專業人士。怎么辦?

        

      Lucene.Net核心類簡介(一)

      • Directory表示索引文件(Lucene.net用來保存用戶扔過來的數據的地方)保存的地方,是抽象類,兩個子類FSDirectory(文件中)、RAMDirectory (內存中)。
      • IndexReader對索引進行讀取的類,對IndexWriter進行寫的類。
      • IndexReader的靜態方法bool IndexExists(Directory directory)判斷目錄directory是否是一個索引目錄。IndexWriter的bool IsLocked(Directory directory) 判斷目錄是否鎖定,在對目錄寫之前會先把目錄鎖定。兩個IndexWriter沒法同時寫一個索引文件。IndexWriter在進行寫操作的時候會自動加鎖,close的時候會自動解鎖。IndexWriter.Unlock方法手動解鎖(比如還沒來得及close IndexWriter 程序就崩潰了,可能造成一直被鎖定)。

      創建索引庫操作:

       

      • 構造函數:IndexWriter(Directory dir, Analyzer a, bool create, MaxFieldLength mfl)因為IndexWriter把輸入寫入索引的時候,Lucene.net是把寫入的文件用指定的分詞器將文章分詞(這樣檢索的時候才能查的快),然后將詞放入索引文件。
      • void AddDocument(Document doc),向索引中添加文檔(Insert)。Document類代表要索引的文檔(文章),最重要的方法Add(Field field),向文檔中添加字段。Document是一片文檔,Field是字段(屬性)。Document相當于一條記錄Field相當于字段
      • Field類的構造函數 Field(string name, string value, Field.Store store, Field.Index index, Field.TermVector termVector): name表示字段名; value表示字段值; store表示是否存儲value值,可選值 Field.Store.YES存儲, Field.Store.NO不存儲, Field.Store.COMPRESS壓縮存儲;默認只保存分詞以后的一堆詞,而不保存分詞之前的內容,搜索的時候無法根據分詞后的東西還原原文,因此如果要顯示原文(比如文章正文)則需要設置存儲。 index表示如何創建索引,可選值Field.Index. NOT_ANALYZED ,不創建索引,Field.Index. ANALYZED,創建索引;創建索引的字段才可以比較好的檢索。是否碎尸萬段!是否需要按照這個字段進行“全文檢索”。 termVector表示如何保存索引詞之間的距離。“北京歡迎你們大家”,索引中是如何保存“北京”和“大家”之間“隔多少單詞”。方便只檢索在一定距離之內的詞。

       

      private void CreateIndex()
              {
                  //索引庫存放在這個文件夾里
                  string indexPath = ConfigurationManager.AppSettings["pathIndex"];
                  //Directory表示索引文件保存的地方,是抽象類,兩個子類FSDirectory表示文件中,RAMDirectory 表示存儲在內存中
                  FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());
                  //判斷目錄directory是否是一個索引目錄。
                  bool isUpdate = IndexReader.IndexExists(directory);
                  logger.Debug("索引庫存在狀態:"+isUpdate);
                  if (isUpdate)
                  {
                      if (IndexWriter.IsLocked(directory))
                      {
                          IndexWriter.Unlock(directory);
                      }
                  }
                  //第三個參數為是否創建索引文件夾,Bool Create,如果為True,則新創建的索引會覆蓋掉原來的索引文件,反之,則不必創建,更新即可。
                  IndexWriter write = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, IndexWriter.MaxFieldLength.UNLIMITED);
      
                  WebClient wc = new WebClient();
                  //編碼,防止亂碼
                  wc.Encoding = Encoding.UTF8;
                  int maxID;
                  try
                  {
                      //讀取rss,獲得第一個item中的鏈接的編號部分就是最大的帖子編號
                      maxID = GetMaxID();
                  }
                  catch (WebException webEx)
                  {
                      logger.Error("獲得最大帖子號出錯",webEx);
                      return;
                      
                  }
                  for (int i = 1; i <= maxID; i++)
                  {
                      try
                      {
                          string url = "http://localhost:8080/showtopic-" + i + ".aspx";
                          logger.Debug("開始下載:"+url);
                          string html = wc.DownloadString(url);
                          HTMLDocumentClass doc = new HTMLDocumentClass();
      
                          doc.designMode = "on";//不讓解析引擎嘗試去執行
                          doc.IHTMLDocument2_write(html);
                          doc.close();
      
                          string title = doc.title;
                          string body = doc.body.innerText;
                          //為避免重復索引,先輸出number=i的記錄,在重新添加
                          write.DeleteDocuments(new Term("number", i.ToString()));
      
                          Document document = new Document();
                          //Field為字段,只有對全文檢索的字段才分詞,Field.Store是否存儲
                          document.Add(new Field("number", i.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                          document.Add(new Field("title", title, Field.Store.YES, Field.Index.NOT_ANALYZED));
                          document.Add(new Field("body", body, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
                          write.AddDocument(document);
                          logger.Debug("索引" + i.ToString() + "完畢");
                      }
                      catch (WebException webEx)
                      {
      
                          logger.Error("下載"+i.ToString()+"失敗",webEx);
                      }
      
                  }
                  write.Close();
                  directory.Close();
                  logger.Debug("全部索引完畢");
              }
              //取最大帖子號
              private int GetMaxID()
              {
                  XDocument xdoc = XDocument.Load("Http://localhost:8080/tools/rss.aspx");
                  XElement channel = xdoc.Root.Element("channel");
                  XElement fitstItem = channel.Elements("item").First();
                  XElement link = fitstItem.Element("link");
                  Match match = Regex.Match(link.Value, @"http://localhost:8080/showtopic-(\d+)\.aspx");
                  string id = match.Groups[1].Value;
                  return Convert.ToInt32(id);
              }

      這樣就創建了索引庫,利用WebClient爬去所有網頁的內容,這兒需要你添加引用Microsoft mshtml組件,MSHTML是微軟公司的一個COM組件,該組件封裝了HTML語言中的所有元素及其屬性,通過其提供的標準接口,可以訪問指定網頁的所有元素。

      當然,創建索引庫最好定時給我們自動創建,類似于Windows計劃任務。

      這兒你可以了解Quartz.Net

      • 首先添加對其(我這個版本有兩個,一個是Quartz.dll,還有一個是Common.Logging)的引用,貌似兩個缺一不可,否則會報錯,類似于文件路徑錯誤。
      • 在Global里配置如下:

       

         public class Global : System.Web.HttpApplication
          {
      
              private static ILog logger = LogManager.GetLogger(typeof(Global));
              private IScheduler sched;
              protected void Application_Start(object sender, EventArgs e)
              {
                  //控制臺就放在Main
                  logger.Debug("Application_Start");
                  log4net.Config.XmlConfigurator.Configure();
                  //從配置中讀取任務啟動時間
                  int indexStartHour = Convert.ToInt32(ConfigurationManager.AppSettings["IndexStartHour"]);
                  int indexStartMin = Convert.ToInt32(ConfigurationManager.AppSettings["IndexStartMin"]);
      
      
                  ISchedulerFactory sf = new StdSchedulerFactory();
                  sched = sf.GetScheduler();
                  JobDetail job = new JobDetail("job1", "group1", typeof(IndexJob));//IndexJob為實現了IJob接口的類
                  Trigger trigger = TriggerUtils.MakeDailyTrigger("tigger1", indexStartHour, indexStartMin);//每天10點3分執行
                  trigger.JobName = "job1";
                  trigger.JobGroup = "group1";
                  trigger.Group = "group1";
      
                  sched.AddJob(job, true);
                  sched.ScheduleJob(trigger);
                  //IIS啟動了就不會來了
                  sched.Start();
      
      
              }
      
              protected void Session_Start(object sender, EventArgs e)
              {
      
              }
      
              protected void Application_BeginRequest(object sender, EventArgs e)
              {
      
              }
      
              protected void Application_AuthenticateRequest(object sender, EventArgs e)
              {
      
              }
      
              protected void Application_Error(object sender, EventArgs e)
              {
                  logger.Debug("網絡出現未處理異常:",HttpContext.Current.Server.GetLastError());
              }
      
              protected void Session_End(object sender, EventArgs e)
              {
      
              }
      
              protected void Application_End(object sender, EventArgs e)
              {
                  logger.Debug("Application_End");
                  sched.Shutdown(true);
              }
          }
      • 最后我們的Job去做任務,但需要實現IJob接口

      public class IndexJob:IJob
          {
              private ILog logger = LogManager.GetLogger(typeof(IndexJob));
              public void Execute(JobExecutionContext context)
              {
                  try
                  {
                      logger.Debug("索引開始");
                      CreateIndex();
                      logger.Debug("索引結束");
                  }
                  catch (Exception ex)
                  {
                      logger.Debug("啟動索引任務異常", ex);
                  }
              }
      }

       

       

      Ok,我們的索引庫建立完了,接下來就是搜索了。

      Lucene.Net核心類簡介(二)

       

      • IndexSearcher是進行搜索的類,構造函數傳遞一個IndexReader。IndexSearcher的void Search(Query query, Filter filter, Collector results)方法用來搜索,Query是查詢條件, filter目前傳遞null, results是檢索結果,TopScoreDocCollector.create(1000, true)方法創建一個Collector,1000表示最多結果條數,Collector就是一個結果收集器。
      • Query有很多子類,PhraseQuery是一個子類。 PhraseQuery用來進行多個關鍵詞的檢索,調用Add方法添加關鍵詞,query.Add(new Term("字段名", 關鍵詞)),PhraseQuery. SetSlop(int slop)用來設置關鍵詞之間的最大距離,默認是0,設置了Slop以后哪怕文檔中兩個關鍵詞之間沒有緊挨著也能找到。 query.Add(new Term("字段名", 關鍵詞)) query.Add(new Term("字段名", 關鍵詞2)) 類似于:where 字段名 contains 關鍵詞 and 字段名 contais 關鍵詞2
      • 調用TopScoreDocCollector的GetTotalHits()方法得到搜索結果條數,調用Hits的TopDocs TopDocs(int start, int howMany)得到一個范圍內的結果(分頁),TopDocs的scoreDocs字段是結果ScoreDoc數組, ScoreDoc 的doc字段為Lucene.Net為文檔分配的id(為降低內存占用,只先返回文檔id),根據這個id調用searcher的Doc方法就能拿到Document了(放進去的是Document,取出來的也是Document);調用doc.Get("字段名")可以得到文檔指定字段的值,注意只有Store.YES的字段才能得到,因為Store.NO的沒有保存全部內容,只保存了分割后的詞。

       

       搜索的代碼:

      •      查看盤古分詞文檔找到高亮顯示:

       

             private string Preview(string body,string keyword)
              {
                  PanGu.HighLight.SimpleHTMLFormatter simpleHTMLFormatter = new PanGu.HighLight.SimpleHTMLFormatter("<font color=\"Red\">","</font>");
                  PanGu.HighLight.Highlighter highlighter = new PanGu.HighLight.Highlighter(simpleHTMLFormatter, new Segment());
                  highlighter.FragmentSize = 100;
                  string bodyPreview = highlighter.GetBestFragment(keyword, body);
                  return bodyPreview;
              }
      • 因為我們頁面剛進入需要加載熱詞,為了減輕服務端壓力,緩存的使用能使我們解決這一問題。
      • 既然是熱詞,當然是最近幾天搜索量最多的,故Sql語句需要考慮指定的時間之內的搜索數量的排序。
      public IEnumerable<Model.SearchSum> GetHotWords()
              { 
                  //緩存
                  var data=HttpRuntime.Cache["hotwords"];
                  if (data==null)
                  {
                      IEnumerable<Model.SearchSum> hotWords = DoSelect();
                      HttpRuntime.Cache.Insert("hotwords",hotWords,null,DateTime.Now.AddMilliseconds(30),TimeSpan.Zero );
                      return hotWords;
                  }
                  return (IEnumerable<Model.SearchSum>)data;
              }
              private IEnumerable<Model.SearchSum> DoSelect()
              {
                  DataTable dt = SqlHelper.ExecuteDataTable(@"
      select top 5 Keyword,count(*) as searchcount  from keywords 
      where datediff(day,searchdatetime,getdate())<7
      group by Keyword 
      order by count(*) desc ");
                  List<Model.SearchSum> list = new List<Model.SearchSum>();
                  if (dt!=null&&dt.Rows!=null&&dt.Rows.Count>0)
                  {
                      foreach (DataRow row in dt.Rows)
                      {
                          Model.SearchSum oneModel=new Model.SearchSum ();
                          oneModel.Keyword = Convert.ToString(row["keyword"]);
                          oneModel.SearchCount = Convert.ToInt32(row["SearchCount"]);
                          list.Add(oneModel);
                      }
                  }
                  return list;
              }
      • 搜索建議,類似于Baidu搜索時下拉提示框,Jquery UI模擬,下面是獲取根據搜索數量最多的進行排序,得到IEnumerable<Model.SearchSum>集合

       

       public IEnumerable<Model.SearchSum> GetSuggestion(string kw)
              {
                  DataTable dt = SqlHelper.ExecuteDataTable(@"select top 5 Keyword,count(*) as searchcount  from keywords 
      where datediff(day,searchdatetime,getdate())<7
      and keyword like @keyword
      group by Keyword 
      order by count(*) desc",new SqlParameter("@keyword","%"+kw+"%"));
                  List<Model.SearchSum> list = new List<Model.SearchSum>();
                  if (dt != null && dt.Rows != null && dt.Rows.Count > 0)
                  {
                      foreach (DataRow row in dt.Rows)
                      {
                          Model.SearchSum oneModel = new Model.SearchSum();
                          oneModel.Keyword = Convert.ToString(row["keyword"]);
                          oneModel.SearchCount = Convert.ToInt32(row["SearchCount"]);
                          list.Add(oneModel);
                      }
                  }
                  return list;
              }

       

      • 最關鍵的搜索代碼,詳見注釋和上面Lucene.Net核心類二:

       

             protected void Page_Load(object sender, EventArgs e)
              {
                  //加載熱詞
      
                  hotwordsRepeater.DataSource = new Dao.KeywordDao().GetHotWords();
                  hotwordsRepeater.DataBind();
                  kw = Request["kw"];
                  if (string.IsNullOrWhiteSpace(kw))
                  {
                      return;
                  }
                  //處理:將用戶的搜索記錄加入數據庫,方便統計熱詞
                  Model.SerachKeyword model = new Model.SerachKeyword();
                  model.Keyword = kw;
                  model.SearchDateTime = DateTime.Now;
                  model.ClinetAddress = Request.UserHostAddress;
      
                  new Dao.KeywordDao().Add(model);
                  //分頁控件
                  MyPage pager = new MyPage();
                  pager.TryParseCurrentPageIndex(Request["pagenum"]);
                  //超鏈接href屬性
                  pager.UrlFormat = "CreateIndex.aspx?pagenum={n}&kw=" + Server.UrlEncode(kw);
                  
                  int startRowIndex = (pager.CurrentPageIndex - 1) * pager.PageSize;
      
      
                  int totalCount = -1;
                  List<SearchResult> list = DoSearch(startRowIndex,pager.PageSize,out totalCount);
                  pager.TotalCount = totalCount;
                  RenderToHTML = pager.RenderToHTML();
                  dataRepeater.DataSource = list;
                  dataRepeater.DataBind();
              }
      
              private List<SearchResult> DoSearch(int startRowIndex,int pageSize,out int totalCount)
              {
                  string indexPath = "C:/Index";
                  FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
                  IndexReader reader = IndexReader.Open(directory, true);
                  //IndexSearcher是進行搜索的類
                  IndexSearcher searcher = new IndexSearcher(reader);
                  PhraseQuery query = new PhraseQuery();
                  
                  foreach (string word in CommonHelper.SplitWord(kw))
                  {
                      query.Add(new Term("body", word));
                  }
                  query.SetSlop(100);//相聚100以內才算是查詢到
                  TopScoreDocCollector collector = TopScoreDocCollector.create(1024, true);//最大1024條記錄
                  searcher.Search(query, null, collector);
                  totalCount = collector.GetTotalHits();//返回總條數
                  ScoreDoc[] docs = collector.TopDocs(startRowIndex, pageSize).scoreDocs;//分頁,下標應該從0開始吧,0是第一條記錄
                  List<SearchResult> list = new List<SearchResult>();
                  for (int i = 0; i < docs.Length; i++)
                  {
                      int docID = docs[i].doc;//取文檔的編號,這個是主鍵,lucene.net分配
                      //檢索結果中只有文檔的id,如果要取Document,則需要Doc再去取
                      //降低內容占用
                      Document doc = searcher.Doc(docID);
                      string number = doc.Get("number");
                      string title = doc.Get("title");
                      string body = doc.Get("body");
      
                      SearchResult searchResult = new SearchResult() { Number = number, Title = title, BodyPreview = Preview(body, kw) };
                      list.Add(searchResult);
      
                  }
                  return list;
              }

       

      Jquery UI模擬Baidu下拉提示和數據的綁定

         <script type="text/javascript">
              $(function () {
                  $("#txtKeyword").autocomplete(
                  {   source: "SearchSuggestion.ashx",
                      select: function (event, ui) { $("#txtKeyword").val(ui.item.value); $("#form1").submit(); }
                  });
              });
          </script>
       <div align="center">
              <input type="text" id="txtKeyword" name="kw" value='<%=kw %>'/>
              <%-- <asp:Button ID="createIndexButton" runat="server" onclick="searchButton_Click" 
                  Text="創建索引庫" />--%>
              <input type="submit" name="searchButton" value="搜索" style="width: 91px" /><br />
          </div>
          <br />
          <ul id="hotwordsUL">
                <asp:Repeater ID="hotwordsRepeater" runat="server">
                  <ItemTemplate>
                      <li><a href='CreateIndex.aspx?kw=<%#Eval("Keyword") %>'><%#Eval("Keyword") %></a></li>
                  </ItemTemplate>
                </asp:Repeater>
          </ul>
          &nbsp;<br />
        
          <asp:Repeater ID="dataRepeater" runat="server" EnableViewState="true">
              <HeaderTemplate>
                  <ul>
              </HeaderTemplate>
              <ItemTemplate>
                  <li>
                      <a href='http://localhost:8080/showtopic-<%#Eval("Number") %>.aspx'><%#Eval("Title") %></a>
                      <br />
                      <%#Eval("BodyPreview") %>
                  
                  </li>
              </ItemTemplate>
              <FooterTemplate>
              </ul>
              </FooterTemplate>
          </asp:Repeater>
          <br />
          <div class="pager"><%=RenderToHTML%></div>

      小結

      很巧,一年前我的微薄上的簽名是七月能有31天,是給我的最大恩惠。現在,此刻,還是很一年前那樣煩躁,不知所措,又是7月31日,那樣的熟悉。

      大三的這個夏天,和往常那樣,靜靜的坐著,看到了凌晨的晨曦,那樣安靜,祥和。

      再過20天,即將投出第一份簡歷,一切都來得那樣快,讓人不知所措。

      或許,明年的7月31日,不再這么悲傷。

      想起了,天下足球里對亨利的描述:

      還是回到倫敦吧,通往海布里的列車一趟一趟運行著,

      這里總會送走過去,迎來新生,

      32歲的亨利就坐在那兒,深情的目光望過去,遠遠都是自己22歲的影子...

       

      點擊附件下載:

       

       

      posted @ 2012-07-31 06:05  木宛哥說編程  閱讀(22901)  評論(106)    收藏  舉報
      multifunction lasers
      訪問人數

      主站蜘蛛池模板: 人妻少妇88久久中文字幕| 欧美啪啪网| 恩施市| 免费中文熟妇在线影片| 久久一本人碰碰人碰| 国产激情一区二区三区午夜| 国产色无码精品视频免费| 人人人澡人人肉久久精品| 亚洲一区二区三区久久受| 99热国产成人最新精品| 欧美xxxxhd高清| 久久久综合香蕉尹人综合网| 国产精品一二三中文字幕| 国产线播放免费人成视频播放 | 韩国无码AV片午夜福利| 亚洲WWW永久成人网站| 日韩高清免费一码二码三码| 边添小泬边狠狠躁视频| 豆国产97在线 | 亚洲| 中国xxx农村性视频| 亚洲一区二区三区十八禁| 天天做天天爱夜夜爽导航| 亚洲一区二区三区影院| 丰满人妻熟妇乱精品视频| 亚洲av日韩av永久无码电影| 久久综合色之久久综合色| 99福利一区二区视频| 日韩av片无码一区二区不卡| 国产精品69人妻我爱绿帽子| 亚洲男女羞羞无遮挡久久丫 | 欧美性猛交xxxx免费看| 成年女人午夜毛片免费视频| 双乳奶水饱满少妇呻吟免费看| 欧美日产国产精品日产| 欧美日韩国产va在线观看免费 | 亚洲综合一区二区三区不卡| 欧美人与动zozo在线播放| 97色成人综合网站| 平乡县| 人妻少妇无码精品专区| 日本伊人色综合网|