下面是我的代码。
Document doc = new Document();
String str = "Lucene in Action"; //first document
doc.add(new Field("title", newString,Field.Store.YES,Field.Index.ANALYZED));
writer.addDocument(doc);
System.out.println(doc.getFields());
如果我需要索引1000个文档,那么我需要为这1000个文档运行上面的代码,如果是,那么我们如何在循环中运行这些代码,我尝试创建类型为Document的数组,但它不允许我这样做。我怎样才能摆脱这个问题呢?
发布于 2019-02-26 02:23:51
您可以创建文档并向其中添加字段一次,然后只需在将文档写入索引之前更改该字段的值
Document doc = new Document();
StringField stringField = new StringField(<your_name>, "", Field.Store.YES);
doc.add(stringField);
....
for (String value : <ListOfStrings>) {
stringField.setStringValue(value);
writer.addDocument(doc);
}
发布于 2019-02-26 02:28:36
这可能不是现成的示例,但我想这个想法本身可能会有所帮助。
您可以将文档创建提取到该方法中:
// methods params should be everything you need every time you want to create a new document
// input param str is instead of this String str = "Lucene in Action";
// it's not used but I left it in case you need it
public Document createDocument(String str,
String newString,
Field.Store storeVal,
Field.Index indexVal) {
final Document doc = new Document();
// if you need to add many fields - you can do it here also
// let's say having this in the loop as well
doc.add(new Field("title", newString, storeVal, indexVal));
return document;
}
现在,如果您多次需要它,您可以尝试如下所示:
for (int i=0; i < 1000; i++) {
final Document doc = createDocument(<!-- pass some args here -->);
writer.addDocument(doc);
System.out.println(doc.getFields()); // just am example. does not mean you need it :)
}
希望它能帮上忙。
Happy Hacking :)
https://stackoverflow.com/questions/54872343
复制相似问题