/// <summary> /// 2.0 删除索引项 /// </summary> /// <param name="id"></param> public void Delete(int id) { IndexTask task = new IndexTask(); task.Id = id; task.Type = TaskType.Delete; queue.Enqueue(task); }
//操作队列的一些列方法: /// <summary> /// 1.0 新增索引项.每新增一篇博客就调用一次Add()方法 /// </summary> /// <param name="id">博客id</param> /// <param name="title">标题</param> /// <param name="msg">内容</param> public void Add(int id, string title, string content) { IndexTask task = new IndexTask() { Id = id, Title = title, Content = content, Type = TaskType.Add }; //将该任务插入队列 queue.Enqueue(task); }
/// <summary> /// Lucene 倒排索引处理 /// 开始→数据→文本→分词器→Field对象→Document对象→IndexWriter→Directory→结束 /// </summary> private void IndexHandler() { //将创建的分词内容放在该目录下. string indexPath = System.Configuration.ConfigurationManager.AppSettings["IndexPath"]; 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, IndexWriter.MaxFieldLength.UNLIMITED); //循环遍历队列 while (queue.Count > 0) { IndexTask task = queue.Dequeue(); writer.DeleteDocuments(new Term("id", task.Id.ToString())); if (task.Type == TaskType.Delete) { continue; } Document document = new Document(); document.Add(new Field("id", task.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); document.Add(new Field("title", task.Title, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS)); document.Add(new Field("content", task.Content, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS)); writer.AddDocument(document); } writer.Close(); directory.Close(); }