lucene搜索
程序员文章站
2022-07-08 19:24:49
...
reader.undeleteAll();//恢复
package com.firstproject.testindex;
import java.io.IOException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
public class UnDeleteDocument {
public static void main(String[] args) throws IOException {
String indexDir="d:/luceneindex";
Directory dir=FSDirectory.getDirectory(indexDir);
IndexReader reader=IndexReader.open(dir);
System.out.println("before undelete:"+reader.numDocs());
// reader.deleteDocuments(new Term("id","1"));
reader.undeleteAll();//恢复
System.out.println("after undelete:"+reader.numDocs());
reader.close();
dir.close();
}
}
设置重要程度
document.setBoost(1.5f);//比较重要
document.setBoost(0.5f);//不重要
package com.firstproject.testindex;
import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
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.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
public class UpdateDocument {
public static void main(String[] args) throws IOException {
Analyzer analyzer=new StandardAnalyzer();
String indexDir="d:/luceneindex";
Directory dir=FSDirectory.getDirectory(indexDir);
IndexReader reader=IndexReader.open(dir);
System.out.println("before delete : "+reader.numDocs());
reader.deleteDocuments(new Term("id","2"));
System.out.println("after delete : "+reader.numDocs());
reader.close();
IndexWriter writer=new IndexWriter(dir,analyzer,true,IndexWriter.MaxFieldLength.LIMITED);
Document document=new Document();
Field field1=new Field("id","2",Field.Store.YES,Field.Index.ANALYZED);
field1.setBoost(1.5f);
document.add(field1);
document.add(new Field("name","Tom",Field.Store.YES,Field.Index.NO));
document.add(new Field("address","tianjin",Field.Store.YES,Field.Index.ANALYZED));
// document.setBoost(1.5f);//比较重要
document.setBoost(0.5f);//不重要
writer.addDocument(document);
writer.close();
reader=IndexReader.open(dir);
System.out.println("after add : "+reader.numDocs());
reader.close();
dir.close();
}
}
Lucene 的常用检索类
IndexSearcher :检索操作的核心组件,用于对 IndexWriter 创建的索引执行,只读的检索操作,工作模式为接收 Query 对象而返回 ScoreDoc对象。
Term :检索的基本单元,标示检索的字段名称和检索对象的值,如Term( “title”, “lucene” )。即表示在 title 字段中搜寻关键词 lucene 。
Query :表示查询的抽象类,由相应的 Term 来标识。
TermQuery :最基本的查询类型,用于匹配含有指定值字段的文档。
TopDocs:保存查询结果的类。
ScoreDoc(Hits):用来装载搜索结果文档队列指针的数组容器。