【问题标题】:Use of Document doc = new Document(); in lucene?使用文档 doc = new Document();在卢森?
【发布时间】:2019-07-19 05:15:57
【问题描述】:

下面是我的代码。

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 类型的数组,但它不允许我这样做。我怎样才能摆脱这个问题?

【问题讨论】:

    标签: java indexing lucene


    【解决方案1】:

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

    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);
    }
    

    【讨论】:

      【解决方案2】:

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

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

      // 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 :) 
      }
      

      希望对你有用。

      黑客快乐 :)

      【讨论】:

        猜你喜欢
        • 2011-06-12
        • 1970-01-01
        • 2012-09-10
        • 2011-03-15
        • 2018-03-13
        • 2020-04-14
        • 1970-01-01
        • 2018-01-01
        • 1970-01-01
        相关资源
        最近更新 更多