1、方法一,通过Term删除
Term构造中没有。Int类型须要转换成Lucene自带的类BytesRef 。 /**
* 依据商品ID删除索引文件
* @param id
*/
public void deleteDocument(int id)
{;
File file = new File("E://index");
IKAnalyzer analyzer = new IKAnalyzer();
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_44, analyzer);
IndexWriter indexWriter = null;
Directory directory;
try {
directory = FSDirectory.open(file);
// 创建 IndexWriter
indexWriter = new IndexWriter(directory, indexWriterConfig);
BytesRef bytes = new BytesRef(NumericUtils.BUF_SIZE_INT);
NumericUtils.intToPrefixCoded(id, 0, bytes);
Term term = new Term(field, bytes); indexWriter.deleteDocuments(term);
indexWriter.close(); } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } 2.方法二,使用NumericRangeQuery /**
* 依据商品ID删除索引文件
* @param id
*/
public void deleteDocument(int id)
{;
File file = new File("E://index"); IKAnalyzer analyzer = new IKAnalyzer();
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_44, analyzer); IndexWriter indexWriter = null; Directory directory;
try {
directory = FSDirectory.open(file);
// 创建 IndexWriter
indexWriter = new IndexWriter(directory, indexWriterConfig);
Query numbericRangeQuery = NumericRangeQuery.newIntRange("ID",id-1, id+1, false, false);
indexWriter.deleteDocuments(numbericRangeQuery);
indexWriter.close(); } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }