add --shared
[pylucene.git] / lucene-java-3.4.0 / lucene / contrib / demo / src / java / org / apache / lucene / demo / SearchFiles.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 java.io.BufferedReader;
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.IOException;
24 import java.io.InputStreamReader;
25 import java.util.Date;
26
27 import org.apache.lucene.analysis.Analyzer;
28 import org.apache.lucene.analysis.standard.StandardAnalyzer;
29 import org.apache.lucene.document.Document;
30 import org.apache.lucene.index.IndexReader;
31 import org.apache.lucene.queryParser.QueryParser;
32 import org.apache.lucene.search.IndexSearcher;
33 import org.apache.lucene.search.Query;
34 import org.apache.lucene.search.ScoreDoc;
35 import org.apache.lucene.search.TopDocs;
36 import org.apache.lucene.store.FSDirectory;
37 import org.apache.lucene.util.Version;
38
39 /** Simple command-line based search demo. */
40 public class SearchFiles {
41
42   private SearchFiles() {}
43
44   /** Simple command-line based search demo. */
45   public static void main(String[] args) throws Exception {
46     String usage =
47       "Usage:\tjava org.apache.lucene.demo.SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-query string] [-raw] [-paging hitsPerPage]\n\nSee http://lucene.apache.org/java/4_0/demo.html for details.";
48     if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) {
49       System.out.println(usage);
50       System.exit(0);
51     }
52
53     String index = "index";
54     String field = "contents";
55     String queries = null;
56     int repeat = 0;
57     boolean raw = false;
58     String queryString = null;
59     int hitsPerPage = 10;
60     
61     for(int i = 0;i < args.length;i++) {
62       if ("-index".equals(args[i])) {
63         index = args[i+1];
64         i++;
65       } else if ("-field".equals(args[i])) {
66         field = args[i+1];
67         i++;
68       } else if ("-queries".equals(args[i])) {
69         queries = args[i+1];
70         i++;
71       } else if ("-query".equals(args[i])) {
72         queryString = args[i+1];
73         i++;
74       } else if ("-repeat".equals(args[i])) {
75         repeat = Integer.parseInt(args[i+1]);
76         i++;
77       } else if ("-raw".equals(args[i])) {
78         raw = true;
79       } else if ("-paging".equals(args[i])) {
80         hitsPerPage = Integer.parseInt(args[i+1]);
81         if (hitsPerPage <= 0) {
82           System.err.println("There must be at least 1 hit per page.");
83           System.exit(1);
84         }
85         i++;
86       }
87     }
88     
89     IndexSearcher searcher = new IndexSearcher(FSDirectory.open(new File(index)));
90     Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);
91
92     BufferedReader in = null;
93     if (queries != null) {
94       in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), "UTF-8"));
95     } else {
96       in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
97     }
98     QueryParser parser = new QueryParser(Version.LUCENE_31, field, analyzer);
99     while (true) {
100       if (queries == null && queryString == null) {                        // prompt the user
101         System.out.println("Enter query: ");
102       }
103
104       String line = queryString != null ? queryString : in.readLine();
105
106       if (line == null || line.length() == -1) {
107         break;
108       }
109
110       line = line.trim();
111       if (line.length() == 0) {
112         break;
113       }
114       
115       Query query = parser.parse(line);
116       System.out.println("Searching for: " + query.toString(field));
117             
118       if (repeat > 0) {                           // repeat & time as benchmark
119         Date start = new Date();
120         for (int i = 0; i < repeat; i++) {
121           searcher.search(query, null, 100);
122         }
123         Date end = new Date();
124         System.out.println("Time: "+(end.getTime()-start.getTime())+"ms");
125       }
126
127       doPagingSearch(in, searcher, query, hitsPerPage, raw, queries == null && queryString == null);
128
129       if (queryString != null) {
130         break;
131       }
132     }
133     searcher.close();
134   }
135
136   /**
137    * This demonstrates a typical paging search scenario, where the search engine presents 
138    * pages of size n to the user. The user can then go to the next page if interested in
139    * the next hits.
140    * 
141    * When the query is executed for the first time, then only enough results are collected
142    * to fill 5 result pages. If the user wants to page beyond this limit, then the query
143    * is executed another time and all hits are collected.
144    * 
145    */
146   public static void doPagingSearch(BufferedReader in, IndexSearcher searcher, Query query, 
147                                      int hitsPerPage, boolean raw, boolean interactive) throws IOException {
148  
149     // Collect enough docs to show 5 pages
150     TopDocs results = searcher.search(query, 5 * hitsPerPage);
151     ScoreDoc[] hits = results.scoreDocs;
152     
153     int numTotalHits = results.totalHits;
154     System.out.println(numTotalHits + " total matching documents");
155
156     int start = 0;
157     int end = Math.min(numTotalHits, hitsPerPage);
158         
159     while (true) {
160       if (end > hits.length) {
161         System.out.println("Only results 1 - " + hits.length +" of " + numTotalHits + " total matching documents collected.");
162         System.out.println("Collect more (y/n) ?");
163         String line = in.readLine();
164         if (line.length() == 0 || line.charAt(0) == 'n') {
165           break;
166         }
167
168         hits = searcher.search(query, numTotalHits).scoreDocs;
169       }
170       
171       end = Math.min(hits.length, start + hitsPerPage);
172       
173       for (int i = start; i < end; i++) {
174         if (raw) {                              // output raw format
175           System.out.println("doc="+hits[i].doc+" score="+hits[i].score);
176           continue;
177         }
178
179         Document doc = searcher.doc(hits[i].doc);
180         String path = doc.get("path");
181         if (path != null) {
182           System.out.println((i+1) + ". " + path);
183           String title = doc.get("title");
184           if (title != null) {
185             System.out.println("   Title: " + doc.get("title"));
186           }
187         } else {
188           System.out.println((i+1) + ". " + "No path for this document");
189         }
190                   
191       }
192
193       if (!interactive || end == 0) {
194         break;
195       }
196
197       if (numTotalHits >= end) {
198         boolean quit = false;
199         while (true) {
200           System.out.print("Press ");
201           if (start - hitsPerPage >= 0) {
202             System.out.print("(p)revious page, ");  
203           }
204           if (start + hitsPerPage < numTotalHits) {
205             System.out.print("(n)ext page, ");
206           }
207           System.out.println("(q)uit or enter number to jump to a page.");
208           
209           String line = in.readLine();
210           if (line.length() == 0 || line.charAt(0)=='q') {
211             quit = true;
212             break;
213           }
214           if (line.charAt(0) == 'p') {
215             start = Math.max(0, start - hitsPerPage);
216             break;
217           } else if (line.charAt(0) == 'n') {
218             if (start + hitsPerPage < numTotalHits) {
219               start+=hitsPerPage;
220             }
221             break;
222           } else {
223             int page = Integer.parseInt(line);
224             if ((page - 1) * hitsPerPage < numTotalHits) {
225               start = (page - 1) * hitsPerPage;
226               break;
227             } else {
228               System.out.println("No such page");
229             }
230           }
231         }
232         if (quit) break;
233         end = Math.min(numTotalHits, start + hitsPerPage);
234       }
235     }
236   }
237 }