首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在lucene中使用Document doc = new Document()?

在lucene中使用Document doc = new Document()?
EN

Stack Overflow用户
提问于 2019-02-26 02:14:59
回答 2查看 334关注 0票数 0

下面是我的代码。

代码语言:javascript
运行
复制
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的数组,但它不允许我这样做。我怎样才能摆脱这个问题呢?

EN

回答 2

Stack Overflow用户

发布于 2019-02-26 02:23:51

您可以创建文档并向其中添加字段一次,然后只需在将文档写入索引之前更改该字段的值

代码语言:javascript
运行
复制
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);
}
票数 0
EN

Stack Overflow用户

发布于 2019-02-26 02:28:36

这可能不是现成的示例,但我想这个想法本身可能会有所帮助。

您可以将文档创建提取到该方法中:

代码语言:javascript
运行
复制
// 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;
}

现在,如果您多次需要它,您可以尝试如下所示:

代码语言:javascript
运行
复制
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 :)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54872343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档