importjava.util.ArrayList;
importjava.util.List;
importorg.apache.lucene.analysis.Analyzer;
importorg.apache.lucene.document.Document;
importorg.apache.lucene.document.Field;
importorg.apache.lucene.document.TextField;
importorg.apache.lucene.index.DirectoryReader;
importorg.apache.lucene.index.IndexWriter;
importorg.apache.lucene.index.IndexWriterConfig;
importorg.apache.lucene.index.IndexWriterConfig.OpenMode;
importorg.apache.lucene.index.Term;
importorg.apache.lucene.search.IndexSearcher;
importorg.apache.lucene.search.Query;
importorg.apache.lucene.search.ScoreDoc;
importorg.apache.lucene.search.TermQuery;
importorg.apache.lucene.search.TopDocs;
importorg.apache.lucene.store.Directory;
importorg.apache.lucene.store.RAMDirectory;
importcom.chenlb.mmseg4j.analysis.ComplexAnalyzer;
publicclassLuceneTest {
staticAnalyzer analyzer =null;
staticDirectory directory =null;
staticString text ="CSDN.NET - 全球最大中文IT社区,为IT专业技术人员提供最全面的信息传播和服务平台";
staticString text1 ="京华时报1月23日报道 昨天,受一股来自中西伯利亚的强冷空气影响,本市出现大风降温天气,白天最高气温只有零下7摄氏度,同时伴有6到7级的偏北风。";
publicstaticvoidmain(String[] args)throwsException {
analyzer = newComplexAnalyzer();
directory = newRAMDirectory();
IndexWriterConfig iwConfig = newIndexWriterConfig(analyzer);
iwConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
IndexWriter iwriter = newIndexWriter(directory, iwConfig);
List list = newArrayList();
list.add(text);
list.add(text1);
for(String item : list) {
Document doc = newDocument();
doc.add(newTextField("text", item, Field.Store.YES));
iwriter.addDocument(doc);
}
iwriter.close();
DirectoryReader ireader = DirectoryReader.open(directory);
IndexSearcher searcher = newIndexSearcher(ireader);
Query q = newTermQuery(newTerm("text","西伯利亚"));
System.out.println(q);
TopDocs tds = searcher.search(q, 10);
System.out.println("======size:"+ tds.totalHits +"========");
for(ScoreDoc sd : tds.scoreDocs) {
System.out.println(sd.score);
System.out.println(searcher.doc(sd.doc).get("text"));
}
}
}