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); // 执行搜索 |

相关推荐
lhldsg8 小时前
全民健身解决方案小程序开发:从0到1的技术实战
java·数据库·需求分析
jason成都8 小时前
Spring WebFlux 适配达梦新方案|dm‑r2dbc:Netty 异步传输的实验性 R2DBC 驱动
java·后端·spring
泡海椒8 小时前
内置SPI函数库详解:JQuick-Java Builtin工具类实战用法
java·开发语言·python
辰烨chenye9 小时前
LeetCode Hot 100 题解 · 二分篇
java·算法·leetcode
小羊没烦恼!9 小时前
Hello Web API系列教程——Web API与国际化
java·服务器·前端·javascript·php
Elastic 中国社区官方博客9 小时前
教程:使用 ES|QL 进行威胁狩猎
大数据·运维·数据库·elasticsearch·搜索引擎·全文检索·安全威胁分析
小荷才露尖尖角,早有蜻蜓立上头10 小时前
过滤器的4种创建方式
java
大圣编蚕10 小时前
Java ByteArrayInputStream 详解:从入门到实战
java·开发语言·算法
程序员阿明11 小时前
idea把插件啥的不默认放在C盘
java·ide·intellij-idea
linweidong11 小时前
中科闻歌Java面试题及参考答案
java·python·大模型·提示词·ai agent·mcp·rag原理