Use of Document doc = new Document(); in lucene?

If I need to index 1000 documents so do I need to run the above code for that 1000 documents, if yes then how can we run this code in a loop, I tried making array of type Document but it isn't allowing me to do that. How can I get out of this problem?

asked Feb 25, 2019 at 18:14 Muhammad Atif Muhammad Atif 1 1 1 bronze badge

2 Answers 2

You can create document and add field to it once and then just change value of that field before writing document to index

Document doc = new Document(); StringField stringField = new StringField(, "", Field.Store.YES); doc.add(stringField); . for (String value : )
answered Feb 25, 2019 at 18:23 8,708 2 2 gold badges 21 21 silver badges 31 31 bronze badges

This is maybe not ready-to-use-example, but I guess the idea itself could be helpful.

You could extract document creation into the method:

// 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; >

Now if you need it multiple times, you could try something like this:

for (int i=0; i < 1000; i++) < final Document doc = createDocument(); writer.addDocument(doc); System.out.println(doc.getFields()); // just am example. does not mean you need it :) > 

Hope it's somehow useful.