Java实现简单的搜索引擎

一、准备工作

在开始实现搜索引擎之前,需要准备以下工作:

  1. 编译环境:需要在本地安装JDK环境,并配置好对应的环境变量。

  2. Maven管理工具:Maven是一个Java项目管理工具,能够自动下载所需的依赖库,并管理项目的编译、测试、打包等过程。

  3. Lucene搜索引擎库:Lucene是一种高效的文本搜索引擎库,它提供了全文检索、模糊搜索、分词等功能,是实现搜索引擎的核心组件。

二、创建项目

1. 引入Lucene库

|---------------------------------------------------------------------------------------------------------------------------------------|
| <dependency> <groupId>org.apache.lucene</groupId> <artifactId>lucene-core</artifactId> <version>8.8.2</version> </dependency> |

2. 添加引用

|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import java.io.File; import java.io.IOException; import java.nio.file.Paths; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; |

三、实现功能

1. 创建索引

将指定目录下的所有文件创建索引,其中文件名和内容会被添加到索引中。

|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| public static void createIndex(String indexDir, String dataDir) throws IOException { Analyzer analyzer = new StandardAnalyzer(); // 创建分词器 Directory dir = FSDirectory.open(Paths.get(indexDir)); // 创建索引目录 IndexWriterConfig config = new IndexWriterConfig(analyzer); // 创建索引配置 IndexWriter writer = new IndexWriter(dir, config); // 创建索引写入器 File[] files = new File(dataDir).listFiles(); // 获取数据文件列表 for (File file : files) { if (!file.isDirectory() && !file.isHidden() && file.exists() && file.canRead()) { Document doc = new Document(); // 创建文档 doc.add(new StringField("filename", file.getName(), Field.Store.YES)); // 添加文件名字段 doc.add(new TextField("content", new String(Files.readAllBytes(file.toPath())), Field.Store.NO)); // 添加文件内容字段 writer.addDocument(doc); // 写入索引 } } writer.commit(); // 提交写入 writer.close(); // 关闭写入器 } |

2. 搜索文件

该方法会执行搜索,并输出匹配的文件名。

|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| public static void search(String indexDir, String queryStr, int maxHits) throws IOException, ParseException { Analyzer analyzer = new StandardAnalyzer(); // 创建分词器 Directory dir = FSDirectory.open(Paths.get(indexDir)); // 创建索引目录 IndexReader reader = DirectoryReader.open(dir); // 创建索引读取器 IndexSearcher searcher = new IndexSearcher(reader); // 创建索引搜索器 String[] fields = {"filename", "content"}; // 指定搜索字段 QueryParser parser = new MultiFieldQueryParser(fields, analyzer); // 创建多字段查询解析器 parser.setDefaultOperator(QueryParser.Operator.OR); // 指定搜索模式 TopDocs hits = searcher.search(parser.parse(queryStr), maxHits); // 执行搜索 System.out.println("Total hits: " + hits.totalHits.value); // 输出结果总数 for (ScoreDoc scoreDoc : hits.scoreDocs) { Document doc = searcher.doc(scoreDoc.doc); // 获取匹配的文档 System.out.println("File name: " + doc.get("filename")); // 输出匹配的文件名 } } |

3. 示例说明

以下是两条实现搜索引擎的示例说明。

1. 搜索本地文件

假设我们需要搜索本地C盘下的所有txt文件,我们可以使用以下代码:

|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| String indexDir = "C:/luceneIndex"; // 索引目录 String dataDir = "C:/data"; // 数据目录 String queryStr = "lucene"; // 查询字符串 int maxHits = 10; // 最大结果数量 createIndex(indexDir, dataDir); // 创建索引 search(indexDir, queryStr, maxHits); // 执行搜索 |

2. 搜索网络数据

假设我们需要从某个网站中搜索所有包含关键字的链接,我们可以使用以下代码:

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| String indexDir = "C:/luceneIndex"; // 索引目录 String url = "http://example.com/search?q=lucene"; // 查询链接 String queryStr = "example"; // 查询字符串 int maxHits = 10; // 最大结果数量 DocumentFetcher documentFetcher = new DocumentFetcher(url); String data = documentFetcher.getContent(); createIndex(indexDir, data); // 创建索引 search(indexDir, queryStr, maxHits); // 执行搜索 |

相关推荐
TlYf NTLE1 分钟前
Spring Boot3.3.X整合Mybatis-Plus
spring boot·后端·mybatis
rOuN STAT6 分钟前
MySQL:基础操作(增删查改)
java
→长歌8 分钟前
2026Java面试30题精解
java·python·面试
SHoM SSER10 分钟前
Spring Boot性能提升的核武器,速度提升500%!
java·spring boot·后端
weixin_4250230018 分钟前
Spring Boot 2.7 + JDK8 集成 Knife4j 4.1.0 教程(仅展示带注解接口)
java·spring boot·后端
追风林28 分钟前
arthas 插件 使用中文
java
rleS IONS33 分钟前
Spring Boot(七):Swagger 接口文档
java·spring boot·后端
AI浩36 分钟前
别卷 Prompt 了,2026 年 AI 工程的新战场是 Harness
java·人工智能·prompt
IT从业者张某某36 分钟前
Dockerfile详解
java·开发语言
BPM_宏天低代码1 小时前
【宏天源码】CRM系统的通信中心:邮件/短信/企微消息集成
java·spring boot·freemarker·crm系统