当前位置:

首页 > 编程开发 > springboot中集成ES怎么实现磁盘文件全文检索功能

springboot中集成ES怎么实现磁盘文件全文检索功能

整体架构考虑到磁盘文件分布到不同的设备上,所以采用磁盘扫瞄代理的模式构建系统,即把扫描服务以代理的方式部署到目标磁盘所在的服务器上,作为定时任务执行,索引统一建立到ES中,当然ES采用分布式高可用部署方法,搜索服务和扫描代理部署到一起来简化架构并实现分布式能力。磁盘文件快速检索架构部署ESES(elasticsearch)是本项目唯一依赖的第三方软件,ES支持docker方式部署,以下是部署过程dockerpulldocker.elastic.co/elasticsearch/elasticsearch:

整体架构

考虑到磁盘文件分布到不同的设备上,所以采用磁盘扫瞄代理的模式构建系统,即把扫描服务以代理的方式部署到目标磁盘所在的服务器上,作为定时任务执行,索引统一建立到ES中,当然ES采用分布式高可用部署方法,搜索服务和扫描代理部署到一起来简化架构并实现分布式能力。

springboot中集成ES怎么实现磁盘文件全文检索功能

磁盘文件快速检索架构

部署ES

ES(elasticsearch)是本项目唯一依赖的第三方软件,ES支持docker方式部署,以下是部署过程

docker pull docker.elastic.co/elasticsearch/elasticsearch:6.3.2
docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p 9300:9300 --name es01 docker.elastic.co/elasticsearch/elasticsearch:6.3.2

部署完成后,通过浏览器打开http://localhost:9200,如果正常打开,出现如下界面,则说明ES部署成功。

springboot中集成ES怎么实现磁盘文件全文检索功能

ES界面

工程结构

springboot中集成ES怎么实现磁盘文件全文检索功能

工程结构

依赖包

本项目除了引入springboot的基础starter外,还需要引入ES相关包

  
    
      org.springframework.boot
      spring-boot-starter-data-elasticsearch
    
    
      io.searchbox
      jest
      5.3.3
    
    
      net.sf.jmimemagic
      jmimemagic
      0.1.4
    
  

配置文件

需要将ES的访问地址配置到application.yml里边,同时为了简化程序,需要将待扫描磁盘的根目录(index-root)配置进去,后面的扫描任务就会递归遍历该目录下的全部可索引文件。

server:
 port: @elasticsearch.port@
spring:
 application:
  name: @project.artifactId@
 profiles:
  active: dev
 elasticsearch:
  jest:
   uris: http://127.0.0.1:9200
index-root: /Users/crazyicelee/mywokerspace

索引结构数据定义

因为要求文件所在目录、文件名、文件正文都有能够检索,所以要将这些内容都作为索引字段定义,而且添加ES client要求的JestId来注解id。

package com.crazyice.lee.accumulation.search.data;

import io.searchbox.annotations.JestId;
import lombok.Data;

@Data
public class Article {
  @JestId
  private Integer id;
  private String author;
  private String title;
  private String path;
  private String content;
  private String fileFingerprint;
}

扫描磁盘并创建索引

因为要扫描指定目录下的全部文件,所以采用递归的方法遍历该目录,并标识已经处理的文件以提升效率,在文件类型识别方面采用两种方式可供选择,一个是文件内容更为精准判断(Magic),一种是以文件扩展名粗略判断。这部分是整个系统的核心组件。

这里有个小技巧

对目标文件内容计算MD5值并作为文件指纹存储到ES的索引字段里边,每次在重建索引的时候判断该MD5是否存在,如果存在就不用重复建立索引了,可以避免文件索引重复,也能避免系统重启后重复遍历文件。

package com.crazyice.lee.accumulation.search.service;

import com.alibaba.fastjson.JSONObject;
import com.crazyice.lee.accumulation.search.data.Article;
import com.crazyice.lee.accumulation.search.utils.Md5CaculateUtil;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import lombok.extern.slf4j.Slf4j;
import net.sf.jmimemagic.*;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Component
@Slf4j
public class DirectoryRecurse {

  @Autowired
  private JestClient jestClient;

  //读取文件内容转换为字符串
  private String readToString(File file, String fileType) {
    StringBuffer result = new StringBuffer();
    switch (fileType) {
      case "text/plain":
      case "java":
      case "c":
      case "cpp":
      case "txt":
        try (FileInputStream in = new FileInputStream(file)) {
          Long filelength = file.length();
          byte[] filecontent = new byte[filelength.intValue()];
          in.read(filecontent);
          result.append(new String(filecontent, "utf8"));
        } catch (FileNotFoundException e) {
          log.error("{}", e.getLocalizedMessage());
        } catch (IOException e) {
          log.error("{}", e.getLocalizedMessage());
        }
        break;
      case "doc":
        //使用HWPF组件中WordExtractor类从Word文档中提取文本或段落
        try (FileInputStream in = new FileInputStream(file)) {
          WordExtractor extractor = new WordExtractor(in);
          result.append(extractor.getText());
        } catch (Exception e) {
          log.error("{}", e.getLocalizedMessage());
        }
        break;
      case "docx":
        try (FileInputStream in = new FileInputStream(file); XWPFDocument doc = new XWPFDocument(in)) {
          XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
          result.append(extractor.getText());
        } catch (Exception e) {
          log.error("{}", e.getLocalizedMessage());
        }
        break;
    }
    return result.toString();
  }

  //判断是否已经索引
  private JSONObject isIndex(File file) {
    JSONObject result = new JSONObject();
    //用MD5生成文件指纹,搜索该指纹是否已经索引
    String fileFingerprint = Md5CaculateUtil.getMD5(file);
    result.put("fileFingerprint", fileFingerprint);
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.termQuery("fileFingerprint", fileFingerprint));
    Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex("diskfile").addType("files").build();
    try {
      //执行
      SearchResult searchResult = jestClient.execute(search);
      if (searchResult.getTotal() > 0) {
        result.put("isIndex", true);
      } else {
        result.put("isIndex", false);
      }
    } catch (IOException e) {
      log.error("{}", e.getLocalizedMessage());
    }
    return result;
  }

  //对文件目录及内容创建索引
  private void createIndex(File file, String method) {
    //忽略掉临时文件,以~$起始的文件名
    if (file.getName().startsWith("~$")) return;

    String fileType = null;
    switch (method) {
      case "magic":
        Magic parser = new Magic();
        try {
          MagicMatch match = parser.getMagicMatch(file, false);
          fileType = match.getMimeType();
        } catch (MagicParseException e) {
          //log.error("{}",e.getLocalizedMessage());
        } catch (MagicMatchNotFoundException e) {
          //log.error("{}",e.getLocalizedMessage());
        } catch (MagicException e) {
          //log.error("{}",e.getLocalizedMessage());
        }
        break;
      case "ext":
        String filename = file.getName();
        String[] strArray = filename.split("\\.");
        int suffixIndex = strArray.length - 1;
        fileType = strArray[suffixIndex];
    }

    switch (fileType) {
      case "text/plain":
      case "java":
      case "c":
      case "cpp":
      case "txt":
      case "doc":
      case "docx":
        JSONObject isIndexResult = isIndex(file);
        log.info("文件名:{},文件类型:{},MD5:{},建立索引:{}", file.getPath(), fileType, isIndexResult.getString("fileFingerprint"), isIndexResult.getBoolean("isIndex"));

        if (isIndexResult.getBoolean("isIndex")) break;
        //1. 给ES中索引(保存)一个文档
        Article article = new Article();
        article.setTitle(file.getName());
        article.setAuthor(file.getParent());
        article.setPath(file.getPath());
        article.setContent(readToString(file, fileType));
        article.setFileFingerprint(isIndexResult.getString("fileFingerprint"));
        //2. 构建一个索引
        Index index = new Index.Builder(article).index("diskfile").type("files").build();
        try {
          //3. 执行
          if (!jestClient.execute(index).getId().isEmpty()) {
            log.info("构建索引成功!");
          }
        } catch (IOException e) {
          log.error("{}", e.getLocalizedMessage());
        }
        break;
    }
  }

  public void find(String pathName) throws IOException {
    //获取pathName的File对象
    File dirFile = new File(pathName);

    //判断该文件或目录是否存在,不存在时在控制台输出提醒
    if (!dirFile.exists()) {
      log.info("do not exit");
      return;
    }

    //判断如果不是一个目录,就判断是不是一个文件,时文件则输出文件路径
    if (!dirFile.isDirectory()) {
      if (dirFile.isFile()) {
        createIndex(dirFile, "ext");
      }
      return;
    }

    //获取此目录下的所有文件名与目录名
    String[] fileList = dirFile.list();

    for (int i = 0; i < fileList.length; i++) {
      //遍历文件目录
      String string = fileList[i];
      File file = new File(dirFile.getPath(), string);
      //如果是一个目录,输出目录名后,进行递归
      if (file.isDirectory()) {
        //递归
        find(file.getCanonicalPath());
      } else {
        createIndex(file, "ext");
      }
    }
  }
}

扫描任务

这里采用定时任务的方式来扫描指定目录以实现动态增量创建索引。

package com.crazyice.lee.accumulation.search.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Configuration
@Component
@Slf4j
public class CreateIndexTask {
  @Autowired
  private DirectoryRecurse directoryRecurse;

  @Value("${index-root}")
  private String indexRoot;

  @Scheduled(cron = "* 0/5 * * * ?")
  private void addIndex(){
    try {
      directoryRecurse.find(indexRoot);
      directoryRecurse.writeIndexStatus();
    } catch (IOException e) {
      log.error("{}",e.getLocalizedMessage());
    }
  }
}

搜索服务

这里以restFul的方式提供搜索服务,将关键字以高亮度模式提供给前端UI,浏览器端可以根据返回的JSON进行展示。

package com.crazyice.lee.accumulation.search.web;

import com.alibaba.fastjson.JSONObject;
import com.crazyice.lee.accumulation.search.data.Article;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class Controller {
  @Autowired
  private JestClient jestClient;

  @RequestMapping(value = "/search/{keyword}",method = RequestMethod.GET)
  @ApiOperation(value = "全部字段搜索关键字",notes = "es验证")
  @ApiImplicitParams(
      @ApiImplicitParam(name = "keyword",value = "全文检索关键字",required = true,paramType = "path",dataType = "String")
  )
  public List search(@PathVariable String keyword){
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.queryStringQuery(keyword));

    HighlightBuilder highlightBuilder = new HighlightBuilder();
    //path属性高亮度
    HighlightBuilder.Field highlightPath = new HighlightBuilder.Field("path");
    highlightPath.highlighterType("unified");
    highlightBuilder.field(highlightPath);
    //title字段高亮度
    HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("title");
    highlightTitle.highlighterType("unified");
    highlightBuilder.field(highlightTitle);
    //content字段高亮度
    HighlightBuilder.Field highlightContent = new HighlightBuilder.Field("content");
    highlightContent.highlighterType("unified");
    highlightBuilder.field(highlightContent);

    //高亮度配置生效
    searchSourceBuilder.highlighter(highlightBuilder);

    log.info("搜索条件{}",searchSourceBuilder.toString());

    //构建搜索功能
    Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex( "gf" ).addType( "news" ).build();
    try {
      //执行
      SearchResult result = jestClient.execute( search );
      return result.getHits(Article.class);
    } catch (IOException e) {
      log.error("{}",e.getLocalizedMessage());
    }
    return null;
  }
}

搜索restFul结果测试

这里以swagger的方式进行API测试。其中keyword是全文检索中要搜索的关键字。

springboot中集成ES怎么实现磁盘文件全文检索功能

搜索结果

使用thymeleaf生成UI

集成thymeleaf的模板引擎直接将搜索结果以web方式呈现。模板包括主搜索页和搜索结果页,通过@Controller注解及Model对象实现。


  
    
      
        
        
      
    
                                               更多       
                      
    
           document.querySelectorAll('.con-more').forEach(item => {         item.onclick = () => {         item.style.cssText = 'display: none';         item.parentNode.querySelector('.con-preview').style.cssText = 'max-height: none;';       }});         本文内容来源于互联网,如有侵权请联系删除。
作者最新文章
编程开发
上一篇: mysql怎么删除从库
下一篇: Photoshop快捷键修改在哪里?PS2020快捷键设置方法
相关文章 更多
C++动态数组初始化怎么写?常用语句与代码示例
C++动态数组初始化怎么写?常用语句与代码示例

深入解析C++中动态数组的初始化机制,涵盖new操作符的不同用法、基本类型与类对象的初始化差异,以及为何在现代C++开发中应优先使用std::vector。

using namespace 使用中遇到的问题怎么解决
using namespace 使用中遇到的问题怎么解决

命名空间的基本概念与常见引入问题在C++等编程语言中,命名空间(namespace)是一种将代码标识符(如变量、函数、类名)封装在特定名称下的机制,其主要目的是避免命名冲突,尤其是在大型项目或使用多个第三方库时。使用“using namespace”指令可以将指定命名空间中的所有名称引入当前作用域,

c语言函数递归 实操经验总结:这些技巧很实用
c语言函数递归 实操经验总结:这些技巧很实用

理解递归的基本原理在C语言中,递归是一种函数调用自身的编程技术。要掌握它,首先需要理解其核心思想:将一个复杂的大问题,分解为一个或几个与原问题相似但规模更小的子问题,直到子问题足够简单,可以直接求解。这个过程通常包含两个关键部分:递归出口和递归体。递归出口定义了问题何时不再继续分解,即最简单、可直接

c语言函数递归 怎么选?常见方案对比分析
c语言函数递归 怎么选?常见方案对比分析

递归函数的基本概念与适用场景在C语言编程中,递归是一种函数调用自身的编程技巧。它并非适用于所有问题,但在处理某些具有自相似结构的问题时,能提供极其清晰和优雅的解决方案。递归的核心思想是将一个大规模问题分解为一个或多个同类型但规模更小的子问题,直到子问题简单到可以直接求解。典型的适用场景包括树形结构的

Objective-C 内存管理入门:从 alloc 到 dealloc 的生命周期详解
Objective-C 内存管理入门:从 alloc 到 dealloc 的生命周期详解

理解内存管理的基石在Objective-C的编程世界中,内存管理是开发者必须掌握的核心技能之一。它直接关系到应用的性能、稳定性与资源利用效率。与一些采用自动垃圾回收机制的语言不同,Objective-C在很长一段时间里,依赖一套基于引用计数的、需要开发者部分介入的管理规则。这套规则的核心思想是明确的

如何正确使用 dealloc 以避免 iOS 应用中的内存泄漏
如何正确使用 dealloc 以避免 iOS 应用中的内存泄漏

理解 dealloc 的角色与时机在 iOS 应用开发中,内存管理是保障应用性能与稳定性的基石。dealloc 方法是 Objective-C 中对象生命周期结束时的关键回调,它标志着对象即将被系统回收内存。正确理解其触发时机至关重要:当一个对象的引用计数降为零时,运行时系统会自动调用该对象的 de

深入理解 Objective-C 中的 dealloc 方法:内存管理核心机制
深入理解 Objective-C 中的 dealloc 方法:内存管理核心机制

内存管理的基石在Objective-C的世界里,内存管理是开发者必须掌握的核心技能之一。作为一门在手动引用计数(MRC)时代诞生的语言,Objective-C要求程序员对对象的生命周期有清晰的认识。dealloc方法正是这一生命周期中至关重要的终点站。它是一个实例方法,当对象的引用计数降为零时,系统

理解 native2ascii:Java 国际化开发中的字符编码工具
理解 native2ascii:Java 国际化开发中的字符编码工具

native2ascii 工具的基本定位在Ja va应用程序的国际化与本地化开发过程中,处理非拉丁字符集是一个常见且关键的环节。Ja va内部使用Unicode字符集来统一表示全球各种语言的文字,但其属性文件(.properties)在历史上要求使用ASCII编码,或者更准确地说,要求非ASCII字

如何使用 native2ascii 转换中文字符为 Unicode 转义序列
如何使用 native2ascii 转换中文字符为 Unicode 转义序列

理解 native2ascii 工具的基本用途在软件开发,特别是涉及国际化处理的场景中,开发者常常需要处理不同编码的文本资源。native2ascii 是 Ja va 开发工具包(JDK)中提供的一个命令行实用程序,其主要功能是将包含本地字符编码(非ASCII字符)的文件,转换为包含 Unicode

Java native2ascii 命令详解:解决属性文件乱码问题
Java native2ascii 命令详解:解决属性文件乱码问题

native2ascii 命令的由来与作用在Ja va开发中,处理国际化资源文件是一个常见需求。资源文件通常以.properties格式存储,用于支持多语言界面。然而,Ja va属性文件默认采用ISO-8859-1字符集编码,这导致了一个直接的问题:当文件中包含非拉丁字符(如中文、日文、韩文等)时,

查看更多
精品专题 更多
装机必备
装机必备

正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

Windows
Windows

正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

macOS软件
macOS软件

正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

Mac软件 更多
灵活计算器
灵活计算器
macOS/iOS/Android

灵活计算器是一款笔记式算数应用,支持实时计算、动态关联和云端同步功能。记录、整理和输出之间的过渡会更自然,适合长期写作、做笔记或持续沉淀个人内容。

赤友清理大师
赤友清理大师
macOS

赤友清理大师是一款为 Mac 设计的智能清理优化工具,可精准扫描垃圾、大文件、重复文件等,释放磁盘空间。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

极度公式
极度公式
Windows/macOS/Linux

极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

WINDOWS 更多
Windows 10
Windows 10
Windows

Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。

极度公式
极度公式
Windows/macOS/Linux

极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。

密码键盘
密码键盘
Windows/macOS/iOS/Android

密码键盘是一款兼具安全性与便捷性的高效密码管理器。日常使用里的持续防护和信息管理会更突出,适合把安全控制放进长期使用流程中的场景。