zoukankan      html  css  js  c++  java
  • Lucene创建索引和索引的基本检索(Lucene 之 Hello World)

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

    一、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();
    }

    2、创建的索引文件 

    lucene索引文件

    二、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();
    }

    2、检索结果

    使用“百知”检索结果

    这里写图片描述

    原文出处:

    高志遠, Lucene创建索引和索引的基本检索, https://blog.csdn.net/qq_31871785/article/details/70169743

  • 相关阅读:
    推荐系统(10)—— 进化算法、强化学习
    Throttle Debounce 总结
    文件点击下载
    Mongodb安装及启动正确姿势
    事务的ACID是指什么?
    sqlserver 获取时间字段 每月最后一天 分组(分区)最后一条的记录
    echarts map js或json 地图数据下载
    sqlserver 字段 逗号分隔分组 多行数据
    windows10 中文输入法 增加美式键盘 导致 系统部分语言变成英文
    excel 合并相同内容的单元格 vba
  • 原文地址:https://www.cnblogs.com/ryelqy/p/10104043.html
Copyright © 2011-2022 走看看