pylucene 3.5.0-3
[pylucene.git] / lucene-java-3.5.0 / lucene / contrib / demo / src / java / org / apache / lucene / demo / IndexFiles.java
1 package org.apache.lucene.demo;
2
3 /**
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
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  */
19
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;
33
34 import java.io.BufferedReader;
35 import java.io.File;
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;
41
42 /** Index all text files under a directory.
43  * <p>
44  * This is a command-line application demonstrating simple Lucene indexing.
45  * Run it with no command-line arguments for usage information.
46  */
47 public class IndexFiles {
48   
49   private IndexFiles() {}
50
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];
63         i++;
64       } else if ("-docs".equals(args[i])) {
65         docsPath = args[i+1];
66         i++;
67       } else if ("-update".equals(args[i])) {
68         create = false;
69       }
70     }
71
72     if (docsPath == null) {
73       System.err.println("Usage: " + usage);
74       System.exit(1);
75     }
76
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");
80       System.exit(1);
81     }
82     
83     Date start = new Date();
84     try {
85       System.out.println("Indexing to directory '" + indexPath + "'...");
86
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);
90
91       if (create) {
92         // Create a new index in the directory, removing any
93         // previously indexed documents:
94         iwc.setOpenMode(OpenMode.CREATE);
95       } else {
96         // Add new documents to an existing index:
97         iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
98       }
99
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):
104       //
105       // iwc.setRAMBufferSizeMB(256.0);
106
107       IndexWriter writer = new IndexWriter(dir, iwc);
108       indexDocs(writer, docDir);
109
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):
115       //
116       // writer.forceMerge(1);
117
118       writer.close();
119
120       Date end = new Date();
121       System.out.println(end.getTime() - start.getTime() + " total milliseconds");
122
123     } catch (IOException e) {
124       System.out.println(" caught a " + e.getClass() +
125        "\n with message: " + e.getMessage());
126     }
127   }
128
129   /**
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.
132    * 
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,
136    * using the
137    * <a href="../../../../../contrib-benchmark/org/apache/lucene/benchmark/byTask/tasks/WriteLineDocTask.html"
138    * >WriteLineDocTask</a>.
139    *  
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
143    */
144   static void indexDocs(IndexWriter writer, File file)
145     throws IOException {
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
151         if (files != null) {
152           for (int i = 0; i < files.length; i++) {
153             indexDocs(writer, new File(file, files[i]));
154           }
155         }
156       } else {
157
158         FileInputStream fis;
159         try {
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
164           return;
165         }
166
167         try {
168
169           // make a new, empty document
170           Document doc = new Document();
171
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);
178           doc.add(pathField);
179
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);
190
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"))));
196
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);
201           } else {
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 
204             // path, if present:
205             System.out.println("updating " + file);
206             writer.updateDocument(new Term("path", file.getPath()), doc);
207           }
208           
209         } finally {
210           fis.close();
211         }
212       }
213     }
214   }
215 }