请高手进来帮助解决lucene编程问题
我用的lucene版本是2.0,程序的输出结果为:
查找 : word1
总共找到 2 个文档
=============================
文档的内部ID号:0
path:null
=============================
文档的内部ID号:1
path:null
我想知道为什么path的值始终为null呢! 网上搜索了很久没有找到解决办法。
代码如下:
public class LuceneTest {
public static void buildIndex() throws Exception {
Document doc1 = new Document();
doc1.add(new Field( "contents ", new StringReader( "word1 word ")));
doc1.add(new Field( "path ", new StringReader( "path\\document1.txt ")));
Document doc2 = new Document();
doc2.add(new Field( "contents ", new StringReader( "word2 word1 ")));
doc2.add(new Field( "path ", new StringReader( "path\\document2.txt ")));
IndexWriter writer = new IndexWriter( "c:\\index ",
new StandardAnalyzer(), true);
writer.addDocument(doc1);
writer.addDocument(doc2);
writer.close();
}
public static void main(String[] args) throws Exception {
// 构建索引
buildIndex();
// 使用已经存在索引目录
Searcher searcher = new IndexSearcher( "c:\\index ");
// 使用标准分析器
Analyzer aStandardAnalyzer = new StandardAnalyzer();
// 从标准输入读取查询的字符串
QueryParser parser = new QueryParser( "contents ", aStandardAnalyzer);
String line = "word1 ";
Query query = parser.parse(line);
// 输出要搜索的内容
System.out.println( "查找 : " + query.toString( "contents "));
// 使用searcher对象的search方法进行搜索,返回的是一个Hits类型的对象
Hits hits = searcher.search(query);
// 使用Hits对象的length()方法,输出搜索到的文档的数量
System.out.println( "总共找到 " + hits.length() + " 个文档 ");
for (int i = 0; i < hits.length(); i++) {
Document doc = hits.doc(i);
System.out.println( "============================= ");
// 输出文档的ID编号
System.out.println( "文档的内部ID号: " + hits.id(i));
// 输出文档的存放路径
String path = doc.get( "path ");
System.out.println( "path: " + path);
}
searcher.close();
}
}
[解决办法]
doc1.add(new Field( "contents ", new StringReader( "word1 word ")));
doc1.add(new Field( "path ", new StringReader( "path\\document1.txt ")));
这里这样写
doc1.add(new Field( "contents ", "word1 word "));
doc1.add(new Field( "path ", "path\\document1.txt "));