zoukankan      html  css  js  c++  java
  • lucene 搜索引擎使用案例

    1.使用定时框架Quartz.Net创建索引库,引用类库文件有Common.Logging.dll、Lucene.Net.dll,PanGu.dll,PanGu.HighLight.dll,PanGu.Lucene.Analyzer.dll,Quartz.dll

    public class IndexJob:IJob
        {
            public void Execute(JobExecutionContext context)
            {
                //第一个版本应该保存body和title,搜索结果形成超链接,不显示正文。

    string indexPath = "e:/index";
                FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());
                bool isUpdate = IndexReader.IndexExists(directory);
                if (isUpdate)
                {
                    //如果索引目录被锁定(比如索引过程中程序异常退出),则首先解锁
                    if (IndexWriter.IsLocked(directory))
                    {
                        IndexWriter.Unlock(directory);
                    }
                }
                IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED);
                WebClient wc = new WebClient();
                wc.Encoding = Encoding.UTF8;//否则下载的是乱码

    //todo:读取rss,获得第一个item中的链接的编号部分就是最大的帖子编号

    List<string> listUrl = new List<string>();
                listUrl.Add("http://www.baidu.com");
                listUrl.Add("http://www.google.com.cn");
                listUrl.Add("http://cn.bing.com/");
                for (int i = 0; i < listUrl.Count; i++)
                {
                    string url = listUrl[i];
                    string html = wc.DownloadString(url);
                    try
                    {

    html = wc.DownloadString(url);
                    }
                    catch (WebException ex)
                    {
                        //写入错误日志或者重新请求下载
                        html = wc.DownloadString(url);
                    }
                    HTMLDocumentClass doc = new HTMLDocumentClass();
                    doc.designMode = "on"; //不让解析引擎去尝试运行javascript
                    doc.IHTMLDocument2_write(html);
                    doc.close();

    string title = doc.title;
                    string body = doc.body.innerText;//去掉标签

    //为避免重复索引,所以先删除number=i的记录,再重新添加
                    writer.DeleteDocuments(new Term("number", i.ToString()));

    Document document = new Document();
                    //只有对需要全文检索的字段才ANALYZED
                    document.Add(new Field("number", i.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
                    document.Add(new Field("url", url, 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, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
                    writer.AddDocument(document);

    }
                writer.Close();
                directory.Close();//不要忘了Close,否则索引结果搜不到
            }

    2.在Glabal.asax.cs文件中初始化并启动和关闭定时操作


     

    private IScheduler sched;
            protected void Application_Start(object sender, EventArgs e)
            {

    //每隔一段时间执行任务

    ISchedulerFactory sf = new StdSchedulerFactory();
                sched = sf.GetScheduler();
                JobDetail job = new JobDetail("job1", "group1", typeof(IndexJob));//IndexJob为实现了IJob接口的类
                DateTime ts = TriggerUtils.GetNextGivenSecondDate(null, 5);//5秒后开始第一次运行
                //           TimeSpan interval =  TimeSpan.FromHours(1);//每隔1小时执行一次
                //Trigger trigger = new SimpleTrigger("trigger1", "group1", "job1", "group1", ts, null,
                //                                        SimpleTrigger.RepeatIndefinitely, interval);//每若干小时运行一次,小时间隔由appsettings中的IndexIntervalHour参数指定
                Trigger trigger = TriggerUtils.MakeDailyTrigger("trigger1", 11, 56);
                trigger.JobName = "job1";
                trigger.JobGroup = "group1";
                trigger.Group = "group1";
                sched.AddJob(job, true);
                sched.ScheduleJob(trigger);
                sched.Start();

    }

    protected void Application_End(object sender, EventArgs e)
            {
               // 要关闭任务定时则需要
                sched.Shutdown(true);
            }

     

    3.从创建的索引文件中读取数据

    protected void Button3_Click(object sender, EventArgs e)
            {
                string indexPath = "e:/index";
                string kw = TextBox1.Text;
                FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
                IndexReader reader = IndexReader.Open(directory, true);
                IndexSearcher searcher = new IndexSearcher(reader);
                PhraseQuery query = new PhraseQuery();

    //todo:把用户输入的关键词进行拆词

    foreach (string word in CommonHelper.SplitWord(TextBox1.Text))//先用空格,让用户去分词,空格分隔的就是词“计算机 专业”
                {
                    query.Add(new Term("body", word));
                }
                //query.Add(new Term("body","计算机"));
                //query.Add(new Term("body", "专业"));

    query.SetSlop(100);
                TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);
                searcher.Search(query, null, collector);
                ScoreDoc[] docs = collector.TopDocs(0, collector.GetTotalHits()).scoreDocs;
                List<SearchResult> listResult = 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);//根据id找Document
                    string number = doc.Get("number");
                    string url = doc.Get("url");
                    string title = doc.Get("title");
                    string body = doc.Get("body");

    SearchResult result = new SearchResult();
                    result.Number = number;
                    result.Title = title;
                    result.Url = url;

    result.BodyPreview = Preview(body, TextBox1.Text);

    listResult.Add(result);
                }
                repeaterResult.DataSource = listResult;
                repeaterResult.DataBind();
            }
            private static string Preview(string body, string keyword)
            {
                //创建HTMLFormatter,参数为高亮单词的前后缀 
                PanGu.HighLight.SimpleHTMLFormatter simpleHTMLFormatter =
                       new PanGu.HighLight.SimpleHTMLFormatter("<font color="red">", "</font>");
                //创建 Highlighter ,输入HTMLFormatter 和 盘古分词对象Semgent 
                PanGu.HighLight.Highlighter highlighter =
                                new PanGu.HighLight.Highlighter(simpleHTMLFormatter,
                                new Segment());
                //设置每个摘要段的字符数 
                highlighter.FragmentSize = 100;
                //获取最匹配的摘要段 
                String bodyPreview = highlighter.GetBestFragment(keyword, body);
                return bodyPreview;
            }
            public class SearchResult
            {
                public string Number { get; set; }
                public string Url { get; set; }
                public string Title { get; set; }
                public string BodyPreview { get; set; }
            }

    public class CommonHelper
            {
                public static string[] SplitWord(string str)
                {
                    List<string> list = new List<string>();
                    Analyzer analyzer = new PanGuAnalyzer();
                    TokenStream tokenStream = analyzer.TokenStream("", new StringReader(str));
                    Lucene.Net.Analysis.Token token = null;
                    while ((token = tokenStream.Next()) != null)
                    {
                        list.Add(token.TermText());
                    }
                    return list.ToArray();
                }
            }

     

    lDirectory表示索引文件(Lucene.net用来保存用户扔过来的数据的地方)保存的地方,是抽象类,两个子类FSDirectory(文件中)、RAMDirectory(内存中)。使用的时候别和IO里的Directory弄混了。


     

    l创建FSDirectory的方法,FSDirectory
    directory =FSDirectory.Open(newDirectoryInfo(indexPath),newNativeFSLockFactory()),
    path索引的文件夹路径


     

    lIndexReader对索引进行读取的类,对IndexWriter进行写的类。


     

    lIndexReader的静态方法bool
    IndexExists(Directory
    directory)判断目录directory是否是一个索引目录。IndexWriter的bool
    IsLocked(Directory
    directory)判断目录是否锁定,在对目录写之前会先把目录锁定。两个IndexWriter没法同时写一个索引文件。IndexWriter在进行写操作的时候会自动加锁,close的时候会自动解锁。IndexWriter.Unlock方法手动解锁(比如还没来得及closeIndexWriter程序就崩溃了,可能造成一直被锁定)。


     

    l构造函数:IndexWriter(Directorydir, Analyzer a,bool
    create,MaxFieldLengthmfl)因为IndexWriter把输入写入索引的时候,Lucene.net是把写入的文件用指定的分词器将文章分词(这样检索的时候才能查的快),然后将词放入索引文件。


     

    lvoidAddDocument(Document doc),向索引中添加文档(Insert)。Document类代表要索引的文档(文章),最重要的方法Add(Field field),向文档中添加字段。Document是一片文档,Field是字段(属性)。Document相当于一条记录,Field相当于字段。


     

    l构造函数:IndexWriter(Directorydir, Analyzer a,bool
    create,MaxFieldLengthmfl)因为IndexWriter把输入写入索引的时候,Lucene.net是把写入的文件用指定的分词器将文章分词(这样检索的时候才能查的快),然后将词放入索引文件。


     

    lvoidAddDocument(Document doc),向索引中添加文档(Insert)。Document类代表要索引的文档(文章),最重要的方法Add(Field field),向文档中添加字段。Document是一片文档,Field是字段(属性)。Document相当于一条记录,Field相当于字段。
     
     

    lField类的构造函数
    Field(string name, string value,Field.Storestore,Field.Indexindex,
    Field.TermVectortermVector):



    name表示字段名;value表示字段值;


    •store表示是否存储value值,可选值Field.Store.YES存储,Field.Store.NO不存储,Field.Store.COMPRESS压缩存储;默认只保存分词以后的一堆词,而不保存分词之前的内容,搜索的时候无法根据分词后的东西还原原文,因此如果要显示原文(比如文章正文)则需要设置存储。



    index表示如何创建索引,可选值Field.Index. NOT_ANALYZED


    •,不创建索引,Field.Index. ANALYZED,创建索引;创建索引的字段才可以比较好的检索。是否碎尸万段!是否需要按照这个字段进行“全文检索”。


    •termVector表示如何保存索引词之间的距离。“北京欢迎你们大家”,索引中是如何保存“北京”和“大家”之间“隔多少单词”。方便只检索在一定距离之内的词。


    为什么要把帖子的url做为一个Field,因为要在搜索展示的时候先帖子地址取出来构建超链接,所以Field.Store.YES;一般不需要对url进行检索,所以Field.Index.NOT_ANALYZED
     


    lIndexSearcher是进行搜索的类,构造函数传递一个IndexReader。IndexSearcher的void Search(Queryquery,
    Filterfilter,
    Collector results)方法用来搜索,Query是查询条件,
    filter目前传递null,
    results是检索结果,TopScoreDocCollector.create(1000, true)方法创建一个Collector,1000表示最多结果条数,Collector就是一个结果收集器。


    lQuery有很多子类,PhraseQuery是一个子类。
    PhraseQuery用来进行多个关键词的检索,调用Add方法添加关键词,query.Add(new Term("字段名",关键词)),PhraseQuery.
    SetSlop(int
    slop)用来设置关键词之间的最大距离,默认是0,设置了Slop以后哪怕文档中两个关键词之间没有紧挨着也能找到。


    •query.Add(new Term("字段名",关键词))


    •query.Add(new Term("字段名",关键词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的没有保存全部内容,只保存了分割后的词。
     
    网页采集


    l用mshtml进行html的解析,IE就是使用mshtml进行网页解析的。添加对Microsoft.mshtml的引用(如果是VS2010,修改这个引用的“嵌入互操作类型”为False。(*)“复制本地”设置为True、“特定版本”设置为False,这样在没有安装VS的机器中也可以用。)


    •HTMLDocumentClass
    doc = new HTMLDocumentClass();


    •doc.designMode= "on"; //不让解析引擎去尝试运行javascript


    •doc.IHTMLDocument2_write(要解析的代码);


    •doc.title、doc.body.innerText,更多用法自己探索。


    •所有Dom方法都能在mshtml中调用


    Quartz.Net


    lQuartz.Net是一个定时任务框架,可以实现灵活的定时任务,开发人员只要编写少量的代码就可以实现“每隔1小时执行”、“每天22点执行”、“每月18日的下午执行8次”等各种定时任务。


    lQuartz.Net中的概念:计划者(IScheduler)、工作(IJob)、触发器(Trigger)。给计划者一个工作,让他在Trigger(什么条件下做这件事)触发的条件下执行这个工作


    l将要定时执行的任务的代码写到实现IJob接口的Execute方法中即可,时间到来的时候Execute方法会被调用。


    lCrondTrigger是通过Crond表达式设置的触发器,还有SimpleTrigger等简单的触发器。可以通过TriggerUtils的MakeDailyTrigger、MakeHourlyTrigger等方法简化调用。
     
     
     


    l连接配置信息放到Web.Config的ConnectionStrings段中,而普通的自定义配置则可以写到AppSettings段中,哪些需要配置:索引的路径,被索引的网站url,索引的时间间隔。


    l读取stringindexPath=ConfigurationManager.AppSettings["IndexPath"],使用ConfigurationManager添加引用System.Configuration


    l使用request.MapPath或者Server.MapPath把相对于网站根路径的路径转换为绝对路径(不是转换为http://www.baidu.com/a.aspx,转换为c:/baidu_com/a.aspx)。在定时任务等不在Http线程中取HttpContext.Current得到的是null,因此在定时任务中不能用HttpContext.Current.Server.MapPath方法来转换,要用HostingEnvironment.MapPath,因此可以在其他地方也用HostingEnvironment.MapPath。

     
    在搜索的时候对热门关键词进行统计
    搜索记录
    每次有用户搜索都把用户的搜索行为记录下来,供热门搜索和搜索建议用。三个字段:
    搜索时间、搜索词、访问者IP地址(Request.UserHostAddress)
     SELECT KeyWord,count(*)
    SearchCount FROM so_KeywordLog where KeyWord
    like @kw and datediff(day,searchdatetime,getdate())<7  group byKeyWord order by count(*) desc
    查询7天以内每个词出现的次数
    把查询出来的热词放入缓存中
    HttpRuntime.Cache.Insert("hotwords",list,null,DateTime.Now.AddSeconds(30),TimeSpan.Zero);
    HttpRuntime.Cache["hotwords"]
     
    参考博客:
    http://www.cnblogs.com/MeteorSeed/archive/2012/12/24/2703716.html#five
  • 相关阅读:
    ssh免密码登陆设置时Authentication refused: bad ownership or modes错误解决方法
    centos7下安装python3
    mongodb基本操作
    mongodb之增删改查
    openfire插件开发之IQHander
    centos7下安装MongoDB4.0
    XMPP节之message,presence,IQ介绍
    linux命令 比较两个文件
    关于内存泄露
    一些术语——依赖倒置•控制反转•依赖注入•面向接口编程
  • 原文地址:https://www.cnblogs.com/yxlblogs/p/3188295.html
Copyright © 2011-2022 走看看