lucene hello world

来源:互联网 发布:网络推广的综合方案 编辑:程序博客网 时间:2024/04/19 13:34
public class Test {
public static Version v36 = Version.LUCENE_36;


public static void main(String[] args) throws Exception{
// createIndex();
search("你世");
search("我是");
search("o I'm");
}


public static void createIndex() throws Exception {
Directory directory = null;
directory = FSDirectory.open(new File("e:\\index\\testindex"));
IndexWriter iwriter = null;
iwriter = new IndexWriter(directory, new IndexWriterConfig(
Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36)));
Document doc = new Document();
String content = "hello , I'm wtang, 你好世界";
doc.add(new Field("hello", content, Field.Store.YES,
Field.Index.ANALYZED));
iwriter.addDocument(doc);
iwriter.close();
directory.close();
System.out.println("create index success");
}


public static void search(String q) throws Exception {
IndexReader ireader = IndexReader.open(FSDirectory.open(new File(
"e:\\index\\testindex")));
IndexSearcher isearcher = new IndexSearcher(ireader);
QueryParser parser = new QueryParser(v36, "hello",
new StandardAnalyzer(v36));
Query query = parser.parse(q);
ScoreDoc[] hits = isearcher.search(query, 1000).scoreDocs;
for(ScoreDoc hit : hits){
Document doc = isearcher.doc(hit.doc);
System.out.println(doc.get("hello"));
}
ireader.close();
   isearcher.close();
}


}
原创粉丝点击