这里给出一个demo,希望帮到有需要的朋友,下面这个实例是以图书馆记录图书为原型设计,
下载网址:https://git.oschina.net/johnHust/lucene.git
代码语言:javascript复制 //logger.info("testSortByString start");
Analyzer analyzer = new StandardAnalyzer();
//Analyzer analyzer = new SimpleAnalyzer(); //被lucene6版本淘汰
//Analyzer analyzer = new WhitespaceAnalyzer();//被lucene6版本淘汰
// 1. create the index
Directory index = FSDirectory.open(Paths.get("E:\tmp\index"));
//Directory index = new RAMDirectory();
IndexWriterConfig config = new IndexWriterConfig(analyzer);
config.setOpenMode(OpenMode.CREATE);
代码语言:javascript复制 //创建索引
代码语言:javascript复制 IndexWriter w = new IndexWriter(index, config);
addDoc(w, "Lucene in Action", "193398817",70);
addDoc(w, "lucene for Action", "55320055Z",80);
addDoc(w, "Managing Gigabytes", "55063554A",90);
addDoc(w, "The Art of Computer Science", "9900333X",50);
w.close();
代码语言:javascript复制 //搜索
TermQuery q1 = new TermQuery(new Term("title","Lucene in Action"));
Query q2 = IntPoint.newRangeQuery("price", 60, 100);
BooleanQuery q3 = new Builder().add(q1, Occur.SHOULD).add(q2, Occur.MUST).build();
代码语言:javascript复制 //在使用parser.parse时需要注意在这个过程中会进行分词操作,产生出来的语汇单元很可能不是要检索的内容!!
QueryParser parser = new QueryParser("title",analyzer);
Query q4 = parser.parse("Lucene in Action");
IndexReader reader = DirectoryReader.open(index);
IndexSearcher searcher = new IndexSearcher(reader);
Sort sort =new Sort(new SortField("isbn",SortField.Type.STRING,true));
TopDocs matches = searcher.search(q3, 10,sort);
//TopDocs matches = searcher.search(q4, 10);
for(ScoreDoc doc:matches.scoreDocs){
logger.info("title:" searcher.doc(doc.doc).get("title") "tisbn:" searcher.doc(doc.doc).get("isbn")
"nprice:" searcher.doc(doc.doc).get("price"));
}
index.close();
下面是addDoc方法:
代码语言:javascript复制 private static void updateDoc(IndexWriter w, String title, String isbn,int price) throws IOException {
Document doc = new Document();
//doc.add(new StringField("title", title,Field.Store.YES));
doc.add(new StringField("title", title,Field.Store.YES));
doc.add(new StringField("isbn", isbn, Field.Store.YES));
//Field f = new Field("price",FieldType.LegacyNumericType.INT);
//IntField field = new IntField(name, 6, Field.Store.NO);
doc.add(new NumericDocValuesField("price",price));
doc.add(new IntPoint("price",price));
doc.add(new StoredField("price",price));
//doc.add(new LegacyIntField("price",price, Field.Store.YES));
w.updateDocument(new Term("title","Lucene in Action"), doc);
}