1 package org.apache.lucene.demo;
4 * Licensed to the Apache Software Foundation (ASF) under one or more
5 * contributor license agreements. See the NOTICE file distributed with
6 * this work for additional information regarding copyright ownership.
7 * The ASF licenses this file to You under the Apache License, Version 2.0
8 * (the "License"); you may not use this file except in compliance with
9 * the License. You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
20 import org.apache.lucene.analysis.Analyzer;
21 import org.apache.lucene.analysis.standard.StandardAnalyzer;
22 import org.apache.lucene.document.Document;
23 import org.apache.lucene.document.Field;
24 import org.apache.lucene.document.NumericField;
25 import org.apache.lucene.index.FieldInfo.IndexOptions;
26 import org.apache.lucene.index.IndexWriter;
27 import org.apache.lucene.index.IndexWriterConfig.OpenMode;
28 import org.apache.lucene.index.IndexWriterConfig;
29 import org.apache.lucene.index.Term;
30 import org.apache.lucene.store.Directory;
31 import org.apache.lucene.store.FSDirectory;
32 import org.apache.lucene.util.Version;
34 import java.io.BufferedReader;
36 import java.io.FileInputStream;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.io.InputStreamReader;
40 import java.util.Date;
42 /** Index all text files under a directory.
44 * This is a command-line application demonstrating simple Lucene indexing.
45 * Run it with no command-line arguments for usage information.
47 public class IndexFiles {
49 private IndexFiles() {}
51 /** Index all text files under a directory. */
52 public static void main(String[] args) {
53 String usage = "java org.apache.lucene.demo.IndexFiles"
54 + " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n"
55 + "This indexes the documents in DOCS_PATH, creating a Lucene index"
56 + "in INDEX_PATH that can be searched with SearchFiles";
57 String indexPath = "index";
58 String docsPath = null;
59 boolean create = true;
60 for(int i=0;i<args.length;i++) {
61 if ("-index".equals(args[i])) {
62 indexPath = args[i+1];
64 } else if ("-docs".equals(args[i])) {
67 } else if ("-update".equals(args[i])) {
72 if (docsPath == null) {
73 System.err.println("Usage: " + usage);
77 final File docDir = new File(docsPath);
78 if (!docDir.exists() || !docDir.canRead()) {
79 System.out.println("Document directory '" +docDir.getAbsolutePath()+ "' does not exist or is not readable, please check the path");
83 Date start = new Date();
85 System.out.println("Indexing to directory '" + indexPath + "'...");
87 Directory dir = FSDirectory.open(new File(indexPath));
88 Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);
89 IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_31, analyzer);
92 // Create a new index in the directory, removing any
93 // previously indexed documents:
94 iwc.setOpenMode(OpenMode.CREATE);
96 // Add new documents to an existing index:
97 iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
100 // Optional: for better indexing performance, if you
101 // are indexing many documents, increase the RAM
102 // buffer. But if you do this, increase the max heap
103 // size to the JVM (eg add -Xmx512m or -Xmx1g):
105 // iwc.setRAMBufferSizeMB(256.0);
107 IndexWriter writer = new IndexWriter(dir, iwc);
108 indexDocs(writer, docDir);
110 // NOTE: if you want to maximize search performance,
111 // you can optionally call forceMerge here. This can be
112 // a terribly costly operation, so generally it's only
113 // worth it when your index is relatively static (ie
114 // you're done adding documents to it):
116 // writer.forceMerge(1);
120 Date end = new Date();
121 System.out.println(end.getTime() - start.getTime() + " total milliseconds");
123 } catch (IOException e) {
124 System.out.println(" caught a " + e.getClass() +
125 "\n with message: " + e.getMessage());
130 * Indexes the given file using the given writer, or if a directory is given,
131 * recurses over files and directories found under the given directory.
133 * NOTE: This method indexes one document per input file. This is slow. For good
134 * throughput, put multiple documents into your input file(s). An example of this is
135 * in the benchmark module, which can create "line doc" files, one document per line,
137 * <a href="../../../../../contrib-benchmark/org/apache/lucene/benchmark/byTask/tasks/WriteLineDocTask.html"
138 * >WriteLineDocTask</a>.
140 * @param writer Writer to the index where the given file/dir info will be stored
141 * @param file The file to index, or the directory to recurse into to find files to index
142 * @throws IOException
144 static void indexDocs(IndexWriter writer, File file)
146 // do not try to index files that cannot be read
147 if (file.canRead()) {
148 if (file.isDirectory()) {
149 String[] files = file.list();
150 // an IO error could occur
152 for (int i = 0; i < files.length; i++) {
153 indexDocs(writer, new File(file, files[i]));
160 fis = new FileInputStream(file);
161 } catch (FileNotFoundException fnfe) {
162 // at least on windows, some temporary files raise this exception with an "access denied" message
163 // checking if the file can be read doesn't help
169 // make a new, empty document
170 Document doc = new Document();
172 // Add the path of the file as a field named "path". Use a
173 // field that is indexed (i.e. searchable), but don't tokenize
174 // the field into separate words and don't index term frequency
175 // or positional information:
176 Field pathField = new Field("path", file.getPath(), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS);
177 pathField.setIndexOptions(IndexOptions.DOCS_ONLY);
180 // Add the last modified date of the file a field named "modified".
181 // Use a NumericField that is indexed (i.e. efficiently filterable with
182 // NumericRangeFilter). This indexes to milli-second resolution, which
183 // is often too fine. You could instead create a number based on
184 // year/month/day/hour/minutes/seconds, down the resolution you require.
185 // For example the long value 2011021714 would mean
186 // February 17, 2011, 2-3 PM.
187 NumericField modifiedField = new NumericField("modified");
188 modifiedField.setLongValue(file.lastModified());
189 doc.add(modifiedField);
191 // Add the contents of the file to a field named "contents". Specify a Reader,
192 // so that the text of the file is tokenized and indexed, but not stored.
193 // Note that FileReader expects the file to be in UTF-8 encoding.
194 // If that's not the case searching for special characters will fail.
195 doc.add(new Field("contents", new BufferedReader(new InputStreamReader(fis, "UTF-8"))));
197 if (writer.getConfig().getOpenMode() == OpenMode.CREATE) {
198 // New index, so we just add the document (no old document can be there):
199 System.out.println("adding " + file);
200 writer.addDocument(doc);
202 // Existing index (an old copy of this document may have been indexed) so
203 // we use updateDocument instead to replace the old one matching the exact
205 System.out.println("updating " + file);
206 writer.updateDocument(new Term("path", file.getPath()), doc);