ElasticSearch 【仿】博客園找找看頁面搜索實現

 前言

  前兩天寫了兩篇(一個Python小白5個小時爬蟲經歷一個Python小白5個小時爬蟲經歷 【續】)分別實現了博客園的列表頁博客收集,和數據導入。後來發現博客園只是容許訪問到4000條左右的數據,因而我又根據關鍵字搜索到「找找看」頁面收集。總共數量也很少,不過也夠作測試的了。本博客要講的內容主要是關於ElasticSearch(下文中用ES表示)的。固然也沒有什麼難度,畢竟第三方的包和ES自己的功能就能實現。html

  注意,本人博客偏向實踐總結類,因此理論上的東西比較少,若是不知道什麼叫作ES而且對本文有興趣閱讀的,能夠先補充一下基礎知識,或者牢牢抱着好奇的心態看完本人也很是歡迎。前端

實戰

  數據前階段已經導好了。目前15785條(博客園首頁4000+精華+待審覈+各類關鍵字搜索)node

  

  下面要作的就是扒下博客園找找看頁面的代碼(我沒有用工具,一點一點複製粘貼的,着實也不容易。有沒有好的工具推薦?)首先,建一個Web項目(Core和非Core都行),而後把頁面考進去,調試一下,直到運行demo頁面正常便可。具體頁面樣式可參考:http://zzk.cnblogs.com/s/blogpost?Keywords=netpython

ES對接

  下面就是C#調用ElasticSearch服務了。我用的是Nest。用NuGet安裝就好。Install Package Nest。我裝的是最新5.2.0版本。git

  爲了檢索方便呢,咱們搜索的實體和ES服務器的最好對應,正如上面的截圖同樣。實體類:github

   public class Blog
    {
        public string id
        {
           get;set;
        }
        public string author { get; set; }
        public string title { get; set; }
        public int view_num { get; set; }
        public int comment_num { get; set; }
        public int goods_num { get; set; }
        public string summary { get; set; }
        public string href { get; set; }
        public DateTime create_time { get; set; }
        public string author_url { get; set; }

    }

  由於我用的MVC,因此直接用MVC的方式到前端綁定數據了。數據庫

  

  到此爲止呢,頁面綁定已經結束了。關鍵是數據怎麼出,其實Nest已經幫你作好了一切,不過呢,還須要你在瞭解一下如何調用,我也是下載了NEST源碼看了他的測試用例才學會的。代碼以下:服務器

var nodes = new Uri[]
{
    new Uri("http://myserver1:9200"),
    new Uri("http://myserver2:9200"),
    new Uri("http://myserver3:9200")
};

var pool = new StaticConnectionPool(nodes);
var settings = new ConnectionSettings(pool);
var client = new ElasticClient(settings);

  獲得client以後,調用client.Search<T>()方法工具

 ISearchResponse<Entities.CnBlogs.Blog> response = _builder?.Client.Search<Entities.CnBlogs.Blog>(s =>s
                     .Type("blog")//type
                     .Index(index??_defaultIndex)//index  這裏時cnblogs
                     .From(from) //從第幾條開始
                     .Size(pageSize)//取多少條
                     .Query(q => q.QueryString(qs => qs.Query(keyword).DefaultOperator(Operator.Or)))//根據關鍵字查詢(查詢方式有不少種,這裏只是爲了作簡單演示)
                     .Highlight(h => //設置高亮
                                h.PreTags("<strong>")//改爲strong以符合博客園的樣式
                                 .PostTags("</strong>")//
                                 .Fields(
                                     hf => hf.Field(p => p.title)//標題高亮
                                             .HighlightQuery(q => q
                                                              .Match(m => m
                                                              .Field(p => p.title)
                                                              .Query(keyword)
                                    )
                                ),
                                    hf => hf.Field(p => p.summary)//簡介高亮
                                            .HighlightQuery(q => q
                                                             .Match(m => m
                                                             .Field(p => p.summary)
                                                             .Query(keyword)
                                     )
                                ))
                            )
             );

  接下來,運行一下,看看效果,這裏由於沒有根據關鍵字搜索,因此高亮沒有顯示post

   

  而後,咱們進行關鍵字搜索,輸入net,搜一下試試,效果出來了是否是,不過html標籤沒解析。不要緊,MVC中用  @Html.Raw(「」)就能夠解決啦

  

 

   最終效果:

  

  固然呢,若是你在實踐過程當中發現並無所謂的高亮,那是由於列表出來以後要對列表須要高亮的字段進行處理,處理代碼以下:

     response.Hits.ToList().ForEach(x =>
            {
                if (x.Highlights?.Count > 0)
                {
                    string titleHighlights = string.Join("", x.Highlights["title"].Highlights);
                    string summaryHighlights = string.Join("", x.Highlights["summary"].Highlights);

                    x.Source.title = titleHighlights;
                    x.Source.summary = summaryHighlights;
                }
                result.Add(x.Source);
               
            });

總結

  總體流程其實和數據庫開發是同樣的。添加數據,讀取數據,綁定數據。只不過不一樣的是,蒐集數據使用python爬的。其餘功能均用.NET Core開發。不過仍是處在學習階段,繼續加油吧,本篇到此爲止,若是以爲本篇對您有幫助,點個推薦不介意吧。

  本文代碼稍後將同步到github。https://github.com/dotnetlive/dotnetlive.search/tree/master/src/DotNetLive.Search.Demo

相關文章
相關標籤/搜索