【搜索引擎】J2SE搜索引擎实例
来源:互联网 发布:一件小事毁了人生知乎 编辑:程序博客网 时间:2024/05/30 04:59
- package phz;
- import org.apache.lucene.analysis.standard.StandardAnalyzer;
- import org.apache.lucene.document.Document;
- import org.apache.lucene.document.Field;
- import org.apache.lucene.index.IndexWriter;
- import org.apache.lucene.queryParser.MultiFieldQueryParser;
- import org.apache.lucene.search.BooleanClause;
- import org.apache.lucene.search.Hits;
- import org.apache.lucene.search.IndexSearcher;
- import org.apache.lucene.search.MultiSearcher;
- import org.apache.lucene.search.Query;
- public class LuceneTest {
- public static void main(String[] args) {
- try {
- LuceneTest luceneTest = new LuceneTest();
-
- luceneTest.index();
-
- luceneTest.search("中国 金牌");
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.out.println("ok");
- }
- public void index() throws Exception {
-
- IndexWriter writer1 = new IndexWriter("d://save//",
- new StandardAnalyzer(), true);
- writer1.close();
-
- IndexWriter writer2 = new IndexWriter("d://save//",
- new StandardAnalyzer(), false);
-
- Document doc1 = new Document();
-
- Field field1 = new Field("ArticleTitle", "北京2008年奥运会", Field.Store.YES,
- Field.Index.TOKENIZED);
-
- doc1.add(field1);
-
- Field field2 = new Field("ArticleText", "这是一届创造奇迹、超越梦想的奥运会.......",
- Field.Store.YES, Field.Index.TOKENIZED);
- doc1.add(field2);
-
-
- writer2.addDocument(doc1);
-
- Document doc2 = new Document();
- field1 = new Field("ArticleTitle", "中国获得全球赞誉", Field.Store.YES,
- Field.Index.TOKENIZED);
- doc2.add(field1);
- field2 = new Field("ArticleText", "中国所取得的金牌总数排行榜的榜首........",
- Field.Store.YES, Field.Index.TOKENIZED);
- doc2.add(field2);
- writer2.addDocument(doc2);
-
-
- writer2.close();
- }
- public void search(String serchString) throws Exception {
-
- IndexSearcher indexSearcher = new IndexSearcher("d://save//");
-
- IndexSearcher indexSearchers[] = { indexSearcher };
-
- String[] fields = { "ArticleTitle", "ArticleText" };
-
- BooleanClause.Occur[] clauses = { BooleanClause.Occur.SHOULD,
- BooleanClause.Occur.SHOULD };
-
- Query query = MultiFieldQueryParser.parse(serchString, fields, clauses,
- new StandardAnalyzer());
-
- MultiSearcher searcher = new MultiSearcher(indexSearchers);
-
- Hits h = searcher.search(query);
-
- for (int i = 0; i < h.length(); i++) {
-
- System.out.println(h.doc(i).get("ArticleTitle"));
-
- System.out.println(h.doc(i).get("ArticleText"));
- }
-
- searcher.close();
- }
- }