最近忽然心血来潮想用java写个搜索引擎,经过一天的研究也有小成,把自己写的一个简单的Hello word发给大家看看,希望对大家有所帮助.关于lucene的架包可以在apache的官方网站下载到,如果需要问我要.如果对lucene不了解的可以先看一下我的利用lucene搜索这篇文章,或则到网上去查一下资料.
/*
 * author:shijiajia
 * Created on 2006-8-30
 */
package com.client;

import java.util.Date;

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.index.Term;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;

public class BooleanQueryTest1

  /**

   *
   * @param args
   * @throws Exception
   */ 
  public static void main (String [] args) throws Exception {
    Document doc1 = new Document();
    doc1.add(Field.Text("name", "word1 word2 word3"));
    doc1.add(Field.Keyword("title", "doc1"));
   
    Document doc2 = new Document();
    doc2.add(Field.Text("name", "word1 word4 word5"));
    doc2.add(Field.Keyword("title", "doc2"));
   
    Document doc3 = new Document();
    doc3.add(Field.Text("name", "word1 word2 word6"));
    doc3.add(Field.Keyword("title", "doc3"));
   
    Document doc4 = new Document();
    doc4.add(Field.Text("name", "中人民共和国"));
    doc4.add(Field.Keyword("title", "doc4"));
    IndexWriter writer = new IndexWriter("c:\\index", new StandardAnalyzer(), true);
    writer.addDocument(doc1);
    writer.addDocument(doc2);
    writer.addDocument(doc3);
    writer.addDocument(doc4);
    writer.close();
   
    Query query1 = null;
    Query query2 = null;
    BooleanQuery query = null;
    Hits hits = null;
   
    IndexSearcher searcher = new IndexSearcher("c:\\index");
   
    query1 = new TermQuery(new Term("name","人"));
    query2 = new TermQuery(new Term("name","word2"));
   
    // 构造一个布尔查询
    query = new BooleanQuery();
   
    // 添加两个子查询
    query.add(query1, false, false);
    query.add(query2, false, false);
    /////////
    Date start = new Date();
    hits = searcher.search(query);
    Date end = new Date();
    System.out.println("总共耗时" + (end.getTime()-start.getTime()) + "毫秒" );
    ///////////////////
    printResult(hits, "word1和word2");
   
  }
 
  public static void printResult(Hits hits, String key) throws Exception
  {
    System.out.println("查找 \"" + key + "\" :");
    if (hits != null)
    {
      if (hits.length() == 0)
      {
        System.out.println("没有找到任何结果");
      }
      else
      {
        System.out.println("找到" + hits.length() + "个结果");
        for (int i = 0; i < hits.length(); i++)
        {
          Document d = hits.doc(i);
          String dname = d.get("title");
          System.out.print(dname + "   ");
        }
        System.out.println();
        System.out.println();
      }
    }
  }
}
推荐学lunece的人看一下lucene in action这本书,很不错~~~~~~

posted on 2006-09-08 11:47  施嘉佳  阅读(3153)  评论(7编辑  收藏  举报