Lucene创建索引和索引的基本检索

来源:互联网 发布:解答问题的软件 编辑:程序博客网 时间:2024/05/17 16:57

Author: 百知教育 gaozhy
注:演示代码所使用jar包版本为 lucene-xxx-5.2.0.jar


  1. lucene索引操作

    1. 创建索引代码

      try {    // 1. 指定索引文件存储位置    Directory directory = FSDirectory.open(Paths.get("F:/lucene/index/example01"));    // 2. 创建分词器 标准分词器    StandardAnalyzer analyzer = new StandardAnalyzer();    // 3. 创建索引写入器    IndexWriterConfig config = new IndexWriterConfig(analyzer);    config.setOpenMode(OpenMode.CREATE_OR_APPEND); //索引不存在创建,索引存在追加    IndexWriter indexWriter = new IndexWriter(directory, config);    // 4. 创建索引文档    Document document = new Document();    document.add(new Field("id", "2", StringField.TYPE_STORED ));    document.add(new Field("name", "CoreJava实战",StringField.TYPE_STORED  ));    document.add(new Field("content", "百知金牌讲师 胡鑫哲出品",TextField.TYPE_STORED));    // 5. 添加索引    indexWriter.addDocument(document);    // 6. 释放资源    indexWriter.commit();    indexWriter.close();    directory.close();} catch (Exception e) {    e.printStackTrace();}
      // 索引日期document.add(new Field("date", DateTools.dateToString(new Date(), Resolution.SECOND),StringField.TYPE_STORED));// 索引数字document.add(new IntField("age", 18, Field.Store.YES));
    2. 创建的索引文件
      lucene索引文件
  2. lucene索引的检索

    1. 索引检索代码

      try{    // 1. 获取索引文件    Directory directory = FSDirectory.open(Paths.get("F:/lucene/index/example01"));    // 2. 读取索引文件    IndexReader indexReader = DirectoryReader.open(directory);    // 3. 创建索引检索器    IndexSearcher searcher = new IndexSearcher(indexReader);    // 4. 创建查询条件     QueryParser parser = new QueryParser("content",new StandardAnalyzer()); //第一个参数: 需要检索的域名 第二个参数: 分词器    Query query = parser.parse("百知"); //检索字符串    System.out.println(query.toString());    // 5. 调用检索器检索    TopDocs topDocs = searcher.search(query, 10); //第二个参数:返回结果 10条信息    System.out.println("命中数:"+topDocs.totalHits);    ScoreDoc[] docs = topDocs.scoreDocs;    // 6. 处理查询结果    for (ScoreDoc scoreDoc : docs) {        System.out.print(searcher.doc(scoreDoc.doc).get("id") + " | ");        System.out.print(searcher.doc(scoreDoc.doc).get("name") + " | ");        System.out.print(searcher.doc(scoreDoc.doc).get("content"));        System.out.println();    }    // 7. 释放资源    indexReader.close();    directory.close();}catch(Exception e){    e.printStackTrace();}
      // 日期检索String date = searcher.doc(sd.doc).get("date");if(date != null){    System.out.print(DateTools.stringToDate(date) + " | ");}// 数字检索System.out.println(searcher.doc(sd.doc).get("age"));
    2. 检索结果

      1. 使用“百知”检索结果

        这里写图片描述

      2. 使用“胡鑫哲”检索结果
        这里写图片描述

0 0
原创粉丝点击