如何使用lucene.net,建立索引,索引目录,查询返回结果

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Lucene;
using Lucene.Net;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.DE;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.QueryParsers.Precedence;
using Lucene.Net.Search;
using Lucene.Net.Search.Spans;
using Lucene.Net.Store;
using Lucene.Net.Util;
using NUnit.Framework;

namespace websearch
{
 /// <summary>
 /// WebForm2 的摘要说明。
 /// </summary>
 public class WebSecrch : System.Web.UI.Page
 {
  DateTime mydate=DateTime.Now;
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   if(!Page.IsPostBack)
   {
    Analyzer analyzer = new StandardAnalyzer();
    Directory directory = FSDirectory.GetDirectory(@"c:/tmp/testindex", true);
    bool indexExist = IndexExist(directory);
    IndexWriter iwriter;
    if(indexExist)
    {
     iwriter = new IndexWriter(directory, analyzer, false);
    }
    else
    {
     iwriter = new IndexWriter(directory, analyzer, true);
    }
    Document doc = new Document();
    doc.Add(Field.Keyword("nid","2"));
    doc.Add(Field.Text("title","我是一个人"));
    doc.Add(Field.UnStored("content","请输入你是一个好人的理由"));
    doc.Add(Field.Keyword("addtime",mydate));
    doc.Add(Field.UnStored("other", "nothing"));
    String newsUrl = "/news/viewhtml/test.htm";
    doc.Add(Field.UnIndexed("visiturl", newsUrl));
    iwriter.AddDocument(doc);
    iwriter.Optimize();
    iwriter.Close();
    IndexSearcher isearcher = new IndexSearcher(directory);

    Query query;
    query = QueryParser.Parse("3", "title", analyzer);
    query = QueryParser.Parse("2", "nid", analyzer);
    Hits hits = isearcher.Search(query);

    Response.Write("<font color=red>共找到"+hits.Length()+"条记录</font><br>");

    for (int i = 0; i <hits.Length(); i++)
    {
     Document hitDoc = hits.Doc(i);
     Response.Write("编号:"+hitDoc.Get("nid").ToString()+"<br>");
     Response.Write("标题:"+hitDoc.Get("title").ToString()+"<br>");
     Response.Write("链接:"+hitDoc.Get("visiturl").ToString()+"<br>");
    }
    isearcher.Close();
    directory.Close();
   }
  }
  public static bool IndexExist(Directory indexDir)
  {
   return IndexReader.IndexExists(indexDir);
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion
 }
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页