Lucene 4.4 根据Int类型字段删除索引

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();
             }           
           
    }


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。