lucene不同版本之间的创建索引与查询,稍微有一些不一样。目前lucene的最新版为5.5.0。查看源代码自带的Demo之后,我写基于lucene5.5.0的创建索引与查询方法。以下是源代码:
IndexFiles.java
package com.tongtongxue.lucene; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Date; 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.LongField; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.index.Term; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; public class IndexFiles { public static void main(String[] args) { String indexPath = "E:\\lucene\\02\\index"; String docsPath = "E:\\lucene\\02\\content"; boolean create = true; Path docDir = Paths.get(docsPath); if (!Files.isReadable(docDir)) { System.out.println("Document directory '" +docDir.toAbsolutePath()+ "' does not exist or is not readable, please check the path"); System.exit(1); } Date start = new Date(); try { System.out.println("Indexing to directory '" + indexPath + "'..."); Directory dir = FSDirectory.open(Paths.get(indexPath)); Analyzer analyzer = new StandardAnalyzer(); IndexWriterConfig iwc = new IndexWriterConfig(analyzer); if (create) { // Create a new index in the directory, removing any // previously indexed documents: iwc.setOpenMode(OpenMode.CREATE); } else { // Add new documents to an existing index: iwc.setOpenMode(OpenMode.CREATE_OR_APPEND); } IndexWriter writer = new IndexWriter(dir, iwc); indexDocs(writer, docDir); // NOTE: if you want to maximize search performance, // you can optionally call forceMerge here. This can be // a terribly costly operation, so generally it's only // worth it when your index is relatively static (ie // you're done adding documents to it): // // writer.forceMerge(1); writer.close(); Date end = new Date(); System.out.println(end.getTime() - start.getTime() + " total milliseconds"); } catch (Exception e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); } } static void indexDocs(final IndexWriter writer, Path path) throws IOException { if (Files.isDirectory(path)) { Files.walkFileTree(path, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { try { indexDoc(writer, file, attrs.lastModifiedTime().toMillis()); } catch (IOException ignore) { // don't index files that can't be read. } return FileVisitResult.CONTINUE; } }); } else { indexDoc(writer, path, Files.getLastModifiedTime(path).toMillis()); } } static void indexDoc(IndexWriter writer, Path file, long lastModified) throws IOException { try (InputStream stream = Files.newInputStream(file)) { // make a new, empty document Document doc = new Document(); // Add the path of the file as a field named "path". Use a // field that is indexed (i.e. searchable), but don't tokenize // the field into separate words and don't index term frequency // or positional information: Field pathField = new StringField("path", file.toString(), Field.Store.YES); doc.add(pathField); // Add the last modified date of the file a field named "modified". // Use a LongField that is indexed (i.e. efficiently filterable with // NumericRangeFilter). This indexes to milli-second resolution, which // is often too fine. You could instead create a number based on // year/month/day/hour/minutes/seconds, down the resolution you require. // For example the long value 2011021714 would mean // February 17, 2011, 2-3 PM. doc.add(new LongField("modified", lastModified, Field.Store.NO)); // Add the contents of the file to a field named "contents". Specify a Reader, // so that the text of the file is tokenized and indexed, but not stored. // Note that FileReader expects the file to be in UTF-8 encoding. // If that's not the case searching for special characters will fail. doc.add(new TextField("contents", new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)))); if (writer.getConfig().getOpenMode() == OpenMode.CREATE) { // New index, so we just add the document (no old document can be there): System.out.println("adding " + file); writer.addDocument(doc); } else { // Existing index (an old copy of this document may have been indexed) so // we use updateDocument instead to replace the old one matching the exact // path, if present: System.out.println("updating " + file); writer.updateDocument(new Term("path", file.toString()), doc); } } } }
SearchFiles.java
package com.tongtongxue.lucene; import java.io.IOException; import java.nio.file.Paths; import java.util.Date; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.FSDirectory; public class SearchFiles { public static void main(String[] args) throws Exception { String index = "E:\\lucene\\02\\index"; String field = "contents"; String queryString = "error"; int hitsPerPage = 10; IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(index))); IndexSearcher searcher = new IndexSearcher(reader); Analyzer analyzer = new StandardAnalyzer(); QueryParser parser = new QueryParser(field, analyzer); Query query = parser.parse(queryString); System.out.println("Searching for: " + query.toString(field)); Date start = new Date(); doPagingSearch(searcher, query, hitsPerPage); Date end = new Date(); System.out.println("Time: "+(end.getTime()-start.getTime())+"ms"); reader.close(); } public static void doPagingSearch(IndexSearcher searcher, Query query, int hitsPerPage) throws IOException { TopDocs results = searcher.search(query, 5 * hitsPerPage); ScoreDoc[] hits = results.scoreDocs; if (hits != null && hits.length > 0) { for (ScoreDoc hit : hits) { Document hitDoc = searcher.doc(hit.doc); System.out.println(hitDoc.get("path")); } } } }
相关推荐
### Lucene3.0创建索引 在Lucene3.0中创建索引是一个关键功能,可以帮助用户快速地检索和管理大量的文本数据。本篇文章将详细介绍如何使用Lucene3.0来创建索引,并通过一个具体的例子来演示整个过程。 #### 一、...
**基于Lucene技术的增量索引** 在信息技术领域,全文搜索引擎是处理大量数据查询的关键工具。Apache Lucene是一个开源的全文检索库,被广泛应用于构建高效、可扩展的搜索功能。本文将深入探讨如何利用Lucene实现...
8. **内存与磁盘索引**:Lucene允许在内存中或磁盘上创建索引,这取决于性能和持久性的需求。在5.5.0版本中,对内存管理和磁盘I/O进行了优化,提高了索引和搜索的速度。 9. **分布式搜索**:Solr,基于Lucene的搜索...
1) 提供实时索引的创建、管理 2) Query的创建 详细介绍参照博客:http://blog.csdn.net/xiaojimanman/article/details/20624739 中的介绍
本文档主要探讨了基于Apache Lucene的索引与搜索技术,这是构建高效全文搜索引擎的关键组成部分。Lucene是一个开源的Java库,提供了强大的文本分析、索引和搜索功能,被广泛应用于各种信息检索系统中。 第一章 引言...
在Eclipse环境中运用java,Lucene建索引及查询关键字
本篇文章将详细阐述如何使用Lucene来创建和查询索引,帮助你深入理解其核心概念和操作流程。 ### 1. Lucene基本概念 - **文档(Document)**:在Lucene中,一个文档代表你要索引的信息单元,它可以包含多个字段...
Lucene创建索引步骤: 1、创建Directory(索引位置) 2、创建IndexWrite(写入索引) 3、创建Document对象 4、为Document添加Field(相当于添加属性:类似于表与字段的关系) 5、通过IndexWriter添加文档到索引中
开发者可以创建索引,执行查询,处理结果,并进行必要的文本分析。 **4. 实现流程** 构建基于Lucene的搜索引擎通常涉及以下几个步骤: - **文本预处理**:包括分词、去除停用词、词干提取等,以减少噪声和提高搜索...
文章主要研究和应用了基于Lucene的搜索引擎,其特点是利用开源网络爬虫工具抓取互联网信息,并通过Lucene的API对特定信息进行索引和搜索。下面详细介绍相关知识点。 1. Lucene基础 Lucene是由Apache软件基金会提供...
【基于 Lucene 索引的分析与实现】 在当今信息爆炸的时代,互联网上的数据量呈指数级增长,人们对于高效检索信息的需求日益强烈。Lucene,作为一个强大的Java全文检索库,提供了便捷的索引和搜索功能,为解决海量...
1. **打开索引目录**:与创建索引类似,先打开索引所在的目录。 2. **创建分词器**:同样需要一个分词器来处理查询字符串。 3. **创建索引读取器**:`IndexReader`用于读取索引,从中获取文档信息。 4. **创建...
**Lucene5学习之创建索引入门示例** 在IT领域,搜索引擎的开发与优化是一项关键技术,而Apache Lucene作为一款高性能、全文本搜索库,是许多开发者进行文本检索的首选工具。本文将深入探讨如何使用Lucene5来创建一...
lucene的下载安装包,里面涵盖了很多的jar包,包括常用的lucene-analyzers-common-5.5.0.jar lucene-core-5.5.0.jar lucene-queryparser-5.5.0.jar
本项目以"基于lucene的Swing全文索引构建于查询工具及源程序"为主题,旨在帮助初学者理解和掌握如何利用Lucene和Swing来创建一个桌面应用程序,实现文件的全文索引和查询功能。 Lucene的核心概念包括以下几个部分:...
创建索引是全文检索的基础,它涉及将文本数据结构化为Lucene可以理解和查询的形式。开发者可以通过Analyzer类来处理输入的文本,进行分词、去除停用词等预处理步骤。然后,使用Document类表示要索引的数据,Field类...
1) 提供实时索引的创建、管理 2) Query的创建 详细功能参照博客:http://blog.csdn.net/xiaojimanman/article/details/20624739 中的介绍
Apache Lucene是一个高性能、全文本搜索库,它提供了一个简单的API来创建、维护和搜索索引。在这个项目中,Lucene被用来对处理后的数据建立索引。索引过程包括分词、建立倒排索引等步骤。分词是将文本拆分成关键词的...