`
liuxinglanyue
  • 浏览: 557442 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Lucene 字符编码问题

阅读更多

现在如果一个txt文件中包含了ANSI编码的文本文件和Unicode编码的文本文件,如下图这种:



 当用Lucene来建索引搜索时,这个文档中的内容是搜索不到的。

 

需要搜索的文本在附件中提供。

 

创建索引的源代码:

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class IndexFiles {
	// 主要代码 索引docDir文件夹下文档,索引文件在INDEX_DIR文件夹中
	@SuppressWarnings("deprecation")
	public static void main(String[] args) {

		File indexDir = new File("e:\\Lucene\\index");
		File docDir = new File("e:\\Lucene\\content");

		try {
			// 索引器
			IndexWriter standardWriter = new IndexWriter(FSDirectory
					.open(indexDir), new StandardAnalyzer(
					Version.LUCENE_CURRENT), true,
					IndexWriter.MaxFieldLength.LIMITED);
			// 不建立复合式索引文件,默认的情况下是复合式的索引文件
			standardWriter.setUseCompoundFile(false);
			String[] files = docDir.list();
			for (String fileStr : files) {
				File file = new File(docDir, fileStr);
				if (!file.isDirectory()) {
					Document doc = new Document();
					// 文件名称,可查询,不分词
					String fileName = file.getName().substring(0,
							file.getName().indexOf("."));
					System.out.println("fileName:"+fileName);
					doc.add(new Field("name", fileName, Field.Store.YES,
							Field.Index.NOT_ANALYZED));
					// 文件路径,可查询,不分词
					String filePath = file.getPath();
					doc.add(new Field("path", filePath, Field.Store.YES,
							Field.Index.NOT_ANALYZED));
					// 文件内容,需要检索
					doc.add(new Field("content", new FileReader(file)));
					standardWriter.addDocument(doc);
				}
			}
			standardWriter.optimize();
			// 关闭索引器
			standardWriter.close();
		} catch (IOException e) {
			System.out.println(" caught a " + e.getClass()
					+ "\n with message: " + e.getMessage());
		}
	}
}

 

搜索的源代码:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
 * 检索索引
 */
public class SearchFiles {

	/** Simple command-line based search demo. */
	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws Exception {

		String index = "E:\\Lucene\\index";
		String field = "content";
		String queries = null;
		boolean raw = false;
		// 要显示条数
		int hitsPerPage = 10;

		// searching, so read-only=true
		IndexReader reader = IndexReader.open(
				FSDirectory.open(new File(index)), true); // only

		Searcher searcher = new IndexSearcher(reader);
		Analyzer standardAnalyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);

		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, field,
				standardAnalyzer);
		while (true) {
			if (queries == null) // prompt the user
				System.out.println("Enter query: ");

			String line = in.readLine();

			if (line == null || line.length() == -1)
				break;

			line = line.trim();
			if (line.length() == 0)
				break;

			Query query = parser.parse(line);
			System.out.println("Searching for: " + query.toString(field));

			doPagingSearch(in, searcher, query, hitsPerPage, raw,
					queries == null);
		}
		reader.close();
	}

	public static void doPagingSearch(BufferedReader in, Searcher searcher,
			Query query, int hitsPerPage, boolean raw, boolean interactive)
			throws IOException {

		TopScoreDocCollector collector = TopScoreDocCollector.create(
				hitsPerPage, false);
		searcher.search(query, collector);
		ScoreDoc[] hits = collector.topDocs().scoreDocs;

		int end, numTotalHits = collector.getTotalHits();
		System.out.println(numTotalHits + " total matching documents");

		int start = 0;

		end = Math.min(hits.length, start + hitsPerPage);

		for (int i = start; i < end; i++) {
			Document doc = searcher.doc(hits[i].doc);
			String path = doc.get("path");
			if (path != null) {
				System.out.println((i + 1) + ". " + path);
			} else {
				System.out
						.println((i + 1) + ". " + "No path for this document");
			}
		}
	}
}

 

  • 大小: 24.1 KB
分享到:
评论
1 楼 ralfbawg 2010-12-29  
doc.add(new Field("content", new FileReader(file)));
这个方法换成
doc.add(new Field("contents", new InputStreamReader(new FileInputStream(file.getCanonicalPath()), charset)));

FileReader用的是系统默认的编码,这样就导致一种编码方式的文件可能以另一种编码方式读取进来进行索引,结果导致在检索时,检索不到.

相关推荐

    lucene-4.7.0全套jar包

    - **Codecs模块**:提供了不同的编码方式,用于存储和检索索引,如`lucene-codecs-4.7.0.jar`。 - **Contrib模块**:包含社区贡献的扩展功能,可能包括特殊分词器、搜索建议等,如`lucene-join-4.7.0.jar`、`lucene...

    lucene 搜索中文PDF文档

    在处理中文PDF时,确保选择的解析库能正确处理中文字符集,如UTF-8,以避免乱码问题。 接下来,构建索引是关键步骤。使用Lucene的`Analyzer`类,结合选定的中文分词器,我们可以对提取的PDF文本进行分析和分词。...

    Lucene3.0全文信息检索

    5. **增强的分析器**:Analyzer在3.0中有了更多可定制的选项,可以更好地处理各种语言和文本格式,支持更多的字符集和编码。 6. **更好的国际化支持**:Lucene 3.0增加了对多种语言的支持,包括中文,改进了对非...

    lucene地理位置搜索所用jar包

    3. **地理编码与解码**:使用GeoHash或其他算法将经纬度转换为字符串,便于存储和搜索。GeoHash是一种空间数据结构,能将地理坐标点映射成字符串,便于索引和比较。 4. **设置查询**:创建一个Query对象,可以根据...

    lucene2.0.0

    4. **索引过程**:包括分析(Analyzer)、字段分析(Tokenization)、词项分析(Term Analysis)和编码(Posting)。索引构建完成后,数据以二进制形式存储在磁盘上。 5. **查询解析**:Lucene支持多种查询语法,如...

    Lucene+原理与代码分析完整版

    《Lucene原理与代码分析》全面解析 Lucene是一个开源的全文搜索引擎库,由Apache...本文仅对Lucene做了基础介绍,实际应用中,开发者还需要根据具体需求对Lucene进行深度学习和实践,以充分利用其功能并解决实际问题。

    lucene4.10.3的api的chm合集

    `lucene-analyzers-phonetic-4.10.3.CHM`包含了语音编码分析器,用于实现模糊匹配和拼写纠错。例如,Soundex和Metaphone算法可以将相似发音的单词映射到相同的代码,提高搜索的包容性。 `lucene-analyzers-smartcn-...

    lucene-codecs-4.4.0.zip

    在Lucene 4.4.0中,代码库包括了多种编码解码器,如Lucene40PostingsFormat、Lucene42PostingsFormat等,它们分别负责不同的索引数据结构的序列化和反序列化。这些编码解码器的设计允许开发者根据实际需求选择最优化...

    Lucene In Action

    2. **索引过程**:Lucene的索引过程包括分析、编码和存储。分析阶段,原始文本被分词并转化为索引的术语。编码是为了节省存储空间和提高搜索速度。存储则涉及如何在磁盘上组织这些数据。 3. **查询处理**:Lucene...

    c# 中文分词 LUCENE IKAnalyzer

    1. **字符编码处理**:中文字符通常使用Unicode编码,如UTF-8或GBK,处理中文文本时需要正确处理字符编码以避免乱码问题。 2. **分词算法**:IKAnalyzer采用了一些经典的分词算法,如HMM(Hidden Markov Model)隐...

    lucene3.6.1

    3. **更多工具**:此外, contrib 还包含了一些其他工具,如信息抽取、地理编码、XML解析等,这些工具可以扩展Lucene的应用范围,使其能够处理更复杂的数据类型和应用场景。 总结来说,Lucene 3.6.1不仅强化了其...

    lucene3.0 search

    4. 压缩存储:为了节省存储空间,Lucene会对索引进行压缩,如使用Delta编码、前缀编码等方法。 三、Lucene 3.0的搜索机制 1. 查询解析(Query Parsing):用户输入的查询字符串经过QueryParser解析,转化为Lucene...

    Lucene查询语法

    Lucene提供了多种查询方式,包括程序编码法和字符串构造查询等,下面将详细介绍这些查询方法及其应用场景。 ##### 1. 程序编码法 程序编码法是指通过编写Java代码来构建查询表达式的方式。这种方式灵活性较高,适用...

    lucene索引结构原理

    1. **分词(Tokenization)**:Lucene使用Analyzer进行文本预处理,将输入的字符串分解成一系列独立的词汇单元(tokens)。Analyzer可以根据语言特性进行定制,例如,英文Analyzer会去除标点符号和停用词。 2. **词...

    基于Lucene4.8的空间检索

    2. **地理编码与反编码**:如果需要处理地址字符串,可以集成第三方服务如Google Maps API进行地理编码和反编码。 3. **多维度检索**:除了地理位置外,还可以结合其他属性(如分类或名称)进行复合查询,提供更...

    使用zend Framework的lucene进行全文检索

    这段代码演示了如何使用默认的分词器(`Zend_Search_Lucene_Analysis_Analyzer_Common_Text`)对字符串进行分析,并打印出分词结果。 为了适应中文环境,我们可能需要创建自定义的分词算法。例如,我们可以扩展`...

    lucene4.10.4源码包

    Lucene的查询解析器如`QueryParser`将用户输入的查询字符串转换为`Query`对象。`Query`类及其子类(如`TermQuery`、`BooleanQuery`)定义了不同的查询模式。`Searcher`接口(主要由`IndexSearcher`实现)执行查询,...

    关于Lucene的词典FST深入剖析-申艳超1

    FST是一种压缩的有向无环图(DAG)结构,每个节点代表一个前缀,边则表示字符的转移。这种结构允许快速地查找、比较和遍历词典中的词项。在FST中,每个节点可以关联一个值,这使得它不仅可以用于查找,还可以进行...

Global site tag (gtag.js) - Google Analytics