Lucene中数组的存储与按原顺序检索问题
Great question! The short answer is yes—Lucene will preserve the order of your vars fields exactly as you added them. So if you insert ['a','b','c'], you won’t get a shuffled result like ['b','c','a'] when retrieving them.
Here’s why: When you add fields to a Lucene Document (like in your loop), the document stores these fields in a sequential list that maintains the order of insertion. When you go to retrieve the fields later, methods like Document.getFields("vars") (which returns a list of IndexableField objects) or Document.getValues("vars") (which gives you a string array) will return the fields in the same order you called doc.add(field).
For example, to retrieve your values in order, you could use code like this:
// Get all vars fields in insertion order List<IndexableField> varsFields = doc.getFields("vars"); List<String> orderedValues = new ArrayList<>(); for (IndexableField field : varsFields) { orderedValues.add(field.stringValue()); } // orderedValues will be ["a", "b", "c"]
Or if you prefer a direct array:
String[] varsArray = doc.getValues("vars"); // varsArray will be ["a", "b", "c"]
There’s no standard scenario where Lucene would reorder these stored fields. The only way the order would change is if you explicitly modify the document’s field list after inserting the original fields (which you’re not doing in your code example).
内容的提问来源于stack exchange,提问作者Doua Beri

