我希望为HTML文件建立索引,并能够在收到搜索结果后跳转到相应的标题。
我目前使用HTMLStripCharFilter解析文件。
public class MyAnalyzer extends Analyzer {
public MyAnalyzer() {
super();
}
@Override
protected Reader initReader(String fieldName, Reader reader) {
return new HTMLStripCharFilter(reader);
}
@Override
protected TokenStreamComponents createComponents(String fieldName) {
StandardTokenizer source = new StandardTokenizer();
TokenStream result = new StandardFilter(source);
result = new LowerCaseFilter(result);
return new TokenStreamComponents(source, result);
}
}
indexMyFile方法获取一个HTML文件的路径并创建索引,但当前仅存储文件名。
private static void indexMyFile(IndexWriter writer, Path file,
long lastModified) throws IOException {
try (InputStream stream = Files.newInputStream(file)) {
Document doc = new Document();
Field pathField = new StringField("path", file.toString(),
Field.Store.YES);
doc.add(pathField);
doc.add(new TextField("contents", new BufferedReader(
new InputStreamReader(stream, StandardCharsets.UTF_8))));
writer.addDocument(doc);
}
我的解决方案是在此Lucene文档中添加一个新的TextField,但是目前我不知道代码的标题。 有没有使用Lucene的方法,所以我可以将内容链接到当前标题和文件名?还是我必须使用JSoup或JTidy,并在标题后将文本传递给indexMyFile方法,并为每个标题创建一个Lucene文档,类似于this post?
答案 0 :(得分:0)
我使用JSoup来解析HTML标签。然后,我没有为整个文件建立索引,而是为每个包含几个字段的标题创建了一个文档:
private void indexString(Path path, String title, String heading,
String content) throws IOException {
Document doc = new Document();
doc.add(new Field("title", title, TextField.TYPE_STORED));
doc.add(new Field("heading", heading, TextField.TYPE_STORED));
doc.add(new StringField("path", path.toString(), Field.Store.YES));
doc.add(new StringField("urlHeading", urlHeading, Field.Store.YES));
doc.add(new TextField("contents", content, Store.NO));
writer.addDocument(doc);
}