lucene删除索引中的Document示例

下面的实例是删除索引中的document的实例

package com.cn;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

public class Index {
	
	public static void main(String []args) throws Exception {
		
		String [] ids = {"1","2"};
		String [] unindexed = {"Netherlands","Italy"};
		String [] unstored = {"Amsterdam has lots of bridges","Venice has lots of canals"};
		String [] text = {"Amsterdam","Venice"};
		
		Directory directory = new RAMDirectory();
		IndexWriter indexWriter = new IndexWriter(directory,new IndexWriterConfig(Version.LUCENE_34, new StandardAnalyzer(Version.LUCENE_34)));
		for(int i = 0;i < ids.length;i++){
			Document doc = new Document();
			doc.add(new Field("id",ids[i],Field.Store.YES,Field.Index.NOT_ANALYZED));
			doc.add(new Field("country",unindexed[i],Field.Store.YES,Field.Index.NO));
			doc.add(new Field("contents",unstored[i],Field.Store.NO,Field.Index.ANALYZED));
			doc.add(new Field("city",text[i],Field.Store.YES,Field.Index.ANALYZED));
			indexWriter.addDocument(doc);
		}
		indexWriter.close();
		
		IndexSearcher indexSearcher = new IndexSearcher(directory);
		Term term = new Term("contents","lots");
		Query query = new TermQuery(term);
		int hitCount = indexSearcher.search(query, 10).totalHits;
		System.out.println(hitCount);
		
		indexWriter = new IndexWriter(directory,new IndexWriterConfig(Version.LUCENE_34, new StandardAnalyzer(Version.LUCENE_34)));
		indexWriter.deleteDocuments(new Term("id","1"));
		indexWriter.close();
		
		IndexReader indexReader = IndexReader.open(directory);
		System.out.println(indexReader.numDocs());
		indexReader.close();
		
		indexSearcher = new IndexSearcher(directory);
		System.out.println(indexSearcher.search(query, 10).totalHits);
	}	
}

输出结果:

2
1
1


阅读更多
个人分类: lucene
想对作者说点什么? 我来说一句

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

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭