lucene+paoding亲密接触

来源:互联网 发布:龙之信条妹子捏脸数据 编辑:程序博客网 时间:2024/04/29 00:53

lucene是什么?lucene是一个开源的,广泛应用的,对数据进行索引、查询的一个框架,更详细的介绍请查看www.lucene.com.

 

 

下面简单的描述一下索引和查询过程。

1. 做索引简单过程:

//获取索引存储路径

  String strindexDir = “”;

  File indexDir = new File(strindexDir);

 

 

// 分词器
  Analyzer analyzer = new PaodingAnalyzer(); // 中文分词 庖丁解牛

//获取写索引对象,准备开始做索引,索引对象相当于数据库中的表
   indexWriter = new IndexWriter(indexDir, analyzer, true);

//构造Document对象,Document相当于数据库中 的一条记录
Document doc = new Document();

 

// 给记录中的字段赋值
    doc.add(new Field(“name”, "value", Field.Store.NO, Field.Index.ANALYZED));

    doc.add(new Field(“name”, "value", Field.Store.NO, Field.Index.ANALYZED));

 

//表记录加入表中
    indexWriter.addDocument(doc);

// 做完索引之后,对索引进行优化
   indexWriter.optimize();

 

//关闭资源
   indexWriter.close();

 

2.查询过程

 

//存放查询结果
  List<HashMap<String, String>> rs = new ArrayList<HashMap<String, String>>();

 

//获取分析器,做索引的时候需要分析,查询的时候也需要分析
  Analyzer analyzer = new PaodingAnalyzer();

 

//构造查询对象,queryField是查询那个Field,相当于数据记录的哪个字段,q是查询关键字
  query = new QueryParser(queryField, analyzer).parse(q);

//下面这句是可以看到对查询关键字的分析
   System.out.println("query key analyze result: " + query.toString());
 

//获取索引对象,进行查询
   IndexReader reader = IndexReader.open(indexDir);
   Searcher searcher = new IndexSearcher(reader);
   Hits hits = searcher.search(query);
   searcher.close();
   

//从查询结果中获取信息
   Document doc = null;

    
    HashMap<String, String> item = new HashMap<String, String>();

    item.put("name", "value");

    item.put("name", "value");
    rs.add(item);

//释放资源
   reader.close();

 做索引,查询就被这么短短几行搞定, 如此看来,lucene好简单,甚强大。其实不然,要游刃有余,需深入磨练。

附上俺的demo。