网页设计|网站建设|网站制作|网站策划
 
在线定单
售后服务
下载中心
建站知识
建站流程
售后服务
联系方式
返回首页联系我们网站地图
 
建站知识
 
用dotLucene为数据库内容建立索引

研究了一天,终于把dotLucene将数据库的内容建索引搞定了。

参考网上的资料,写了两个类。

//建立索引的类
public class Indexer
 {
 private IndexWriter writer;
 Document doc = new Document();

 public Indexer(string Directory)
 {
 InitializeIndex(Directory);
 }

 public void InitializeIndex(string Directory)
 {
 writer = new IndexWriter(Directory, new StandardAnalyzer(), true);
 writer.SetUseCompoundFile(true);
 }


 public void AddDocument(string DateAdded , string Description , string URL , string Title )
 {
 doc.Add(Field.Keyword(“date“, DateAdded));
 doc.Add(Field.Text(“description“, Description));
 doc.Add(Field.Text(“url“, URL));
 doc.Add(Field.Text(“title“, Title));
 doc.Add(Field.Keyword(“sortdate“, ReturnSortDate(DateTime.Parse(DateAdded)).ToString()));
 writer.AddDocument(doc);
 }


 private int ReturnSortDate(DateTime DateAdded)
 {
 string thisMonth = DateAdded.Month.ToString();

 if (thisMonth.Length == 1)
 {
 thisMonth = “0“ + thisMonth;
 }

 string thisYear = DateAdded.Year.ToString();
 string thisDay = DateAdded.Day.ToString();

 if( thisDay.Length == 1 )
 {
 thisDay = “0“ + thisDay;
 }

 int time = int.Parse(thisYear+thisMonth +thisDay);


 return time;
 }


 public void Close()
 {
 writer.Optimize();
 writer.Close();
 }
 }//搜索的类
public class Searcher
 {
 private IndexSearcher searcher;

 public Searcher(string Directory)
 {
 searcher = new IndexSearcher(Directory);
 }


 public DataTable Search(string Query, string SortBy)
 {
 DataTable Results = new DataTable();
 Results.Columns.Add(“Title“);
 Results.Columns.Add(“Description“);
 Results.Columns.Add(“URL“);
 Results.Columns.Add(“Published“);

 Query MyQuery = QueryParser.Parse(Query, “description“, new StandardAnalyzer());
 Sort sort = new Sort(SortBy, true);
 Hits Hits = searcher.Search(MyQuery, sort);

 int mTotalRecs = Hits.Length();
 int iCount = 0;
 while (iCount < mTotalRecs)
 {
 Document doc = Hits.Doc(iCount);
 DataRow row = Results.NewRow();
 row[“url“] = doc.Get(“url“);
 row[“Title“] = doc.Get(“title“);
 row[“Description“] = doc.Get(“description“);
 row[“Published“] = doc.Get(“date“);
 Results.Rows.Add(row);

 iCount++;
 }

 searcher.Close();
 return Results;
 }
 }
只要将数据从数据库里读出来,并调用Indexer的AddDocument(),建立索引,然后再调用Searcher的Search方法,就大功告成了。