Tuesday, February 03, 2009

Lucli with Lucene 2.4/Java 6

We recently upgraded at work from Lucene 2.0 to Lucene 2.4 to pick up some performance related bugfixes. I've written before about enhancing Lucli, a command line tool for querying Lucene indexes, written by Dror Matalon. Specifically, I added in a very primitive scripting support, so people could write little Lucli "macros" and run them in batch.

At the time, I assumed that the Lucli code was being maintained and I wanted to contribute my changes back, so I was trying to be as unobtrusive and as well-behaved as possible. Since then, it appears that Lucli is neither actively maintained nor used - I think people with large enterprise-level indexes probably prefer a web based interface - so I figured it would be safe (and educational, given the API changes between Lucene 2.0 and 2.4) to create my own version with Lucene 2.4 and Java 1.6. So here it is.

The code shown below has the following new features, compared to the original Lucli version 2.4 code from which it was adapted.

  1. Rewritten using Java 1.6/Lucene 2.4
  2. Scripting interface described here.
  3. New commands: list, get, remove, analyzer, similarity, orient
  4. Expects queries in Lucene's Query Syntax.
  5. Results display (ITSV) metadata.
  6. Support for multisearcher mode for search based operations
  7. Removed pagination code from Lucli, uses JLine's pagination support instead
  8. New LucliCommands Enum, makes addition of new commands slightly easier than original version.

Rewritten using Java 1.6/Lucene 2.4

This probably benefits me more than anybody else. However, it is more convenient to use the newer Java idioms and results in less (and somewhat more readable, IMO) code. It also resulted in a slightly simpler (one step less) way of adding a new command to Lucli (described in detail later).

My main aim in doing this was to learn the new Lucene 2.4 API, so I guess its a no-brainer. Some changes I am aware of after this exercise are:

  1. The Hits class is deprecated.
  2. Score normalization is no longer done (see this bug for details).
  3. Support for reusable Tokens returned from a TokenStream.
  4. Many improvements on the indexing side.

list

This is functionality I had put in earlier, but the difference is a more natural way (space separated instead of colon separated) of specifying the fields that should show up in the output. The command allows the user to dump a list of Documents from the index in Document Id order. This is probably not all that useful in interactive mode, but it can be used in script mode to answer questions about whether a certain document (or documents) are available in the index or not. Here is a little demo.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
sirocco:~$ lucli.sh                                       
Lucene CLI. Please specify index. Type 'help' for instructions.
lucli> index src/test/resources/movieindex1
Index has 99999 documents
All Fields: [released, body, title]
Indexed Fields: [released, body, title]
lucli> list title
-------------------- Result-#:      0, DocId:      0 --------------------
title            (ITS-): $1,000,000 Chance of a Lifetime
-------------------- Result-#:      1, DocId:      1 --------------------
title            (ITS-): $10,000 Pyramid, The
-------------------- Result-#:      2, DocId:      2 --------------------
title            (ITS-): $100,000 Name That Tune
-------------------- Result-#:      3, DocId:      3 --------------------
title            (ITS-): $25 Million Dollar Hoax
...

get

The get command allows you to print a document with the given document id. A possible use for it is to drill down into a particular document that was found by dumping out the list and pattern matching with grep or similar tool. For example, here is Document 3.

1
2
3
4
5
lucli> get 3
-------------------- Result-#:      0, DocId:      3 --------------------
released         (I-S-): 2004
title            (ITS-): $25 Million Dollar Hoax
lucli>

remove

The remove command allows you to remove a document from the index. Obviously, this is a dangerous command, but it can be useful, for example, when required to quickly remove a document from search results without having to regenerate the index. To delete our document #3, we can do this:

1
2
3
4
5
lucli> remove 3
Document 3 deleted
lucli> get 3
ERROR: attempt to access a deleted document
lucli> 

analyzer

Lucli 2.4 had the Analyzer hard coded to StandardAnalyzer. Since we (probably like quite a few other companies) build our indexes using a custom Analyzer, I needed a way to set the custom Analyzer into Lucli. The 'analyzer' command does this. If no arguments are supplied, the current Analyzer class name is returned. To specify an Analyzer, the class name of the Analyzer must be specified in the 'analyzer' command, the Analyzer class must exist on the classpath, and the Analyzer must have have a public default (zero-argument) constructor. For example:

1
2
3
4
5
lucli> analyzer
Analyzer set: org.apache.lucene.analysis.standard.StandardAnalyzer
lucli> analyzer com.mycompany.customextensions.analysis.MyCustomAnalyzer
Analyzer set: com.mycompany.customextensions.analysis.MyCustomAnalyzer
lucli> 

similarity

Like the Analyzer, Lucli 2.4 uses DefaultSimilarity as its default Similarity implementation. We use a custom similarity implementation for one of our index tiers, so having a way to set this was important for us. The 'similarity' command is similar to the 'analyzer' command. If supplied without arguments, the current Similarity setting is returned. To set a custom Similarity implementation, the full class name of the Similarity implementation must be specified, the Similarity class must exist on the classpath, and the Similarity must have a public default constructor. For example:

1
2
3
4
5
lucli> similarity                                                   
Similarity set: org.apache.lucene.search.DefaultSimilarity
lucli> similarity org.apache.lucene.search.DefaultSimilarity
Similarity set: org.apache.lucene.search.DefaultSimilarity
lucli> 

orient

Lucli was originally intended to serve as an interactive tool, so its display format reflects that. However, when used in batch mode, you typically want to use other Unix (or other) tools on the output, and the one-line-per-document format works better in such cases. So the 'orient' command allows the user to set the orientation. The default is set to vertical. A sample session is shown below, showing the usage of the 'orient' command and the result of setting the orientations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
lucli> orient              
Result orientation is vertical
lucli> search title:fonz
3 total matching documents

-------------------- Result-#:      0, DocId:  15827 --------------------
score                  :  5.563311
released         (I-S-): 1980
title            (ITS-): Fonz and the Happy Days Gang, The
-------------------- Result-#:      1, DocId:  18845 --------------------
score                  :  4.867897
released         (I-S-): 1974
title            (ITS-): Happy Days  - A.K.A. the Fonz  #4.10
-------------------- Result-#:      2, DocId:  14808 --------------------
score                  :  4.172483
released         (I-S-): 1999
title            (ITS-): Family Guy  - The Father, the Son and the Holy Fonz  #4.18
lucli> orient horizontal
lucli> orient
Result orientation is horizontal
lucli> search title:fonz
3 total matching documents

##resultId;docId;score;released;title
0;15827 5.563311;1980;Fonz and the Happy Days Gang, The
1;18845 4.867897;1974;Happy Days  - A.K.A. the Fonz  #4.10
2;14808 4.172483;1999;Family Guy  - The Father, the Son and the Holy Fonz  #4.18
lucli> 

Lucene Query Syntax expected

Lucli 2.4 goes to great lengths to make the query interface behave like a web search box. It takes plain strings, and attempts to match it with every indexable field using a MultiFieldQueryParser. The current one is simpler - it still supports the plain string approach, but matches it to the default field, as shown below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
lucli> explain "fonz"
Rewritten query: body:fonz
16 total matching documents

-------------------- Result-#:      0, DocId:  15828 --------------------
score                  :  2.138932
released         (I-S-): 2000
title            (ITS-): Food 911  - The Spaghetti Kid  #4.33
Explanation            : 2.138932 = (MATCH) fieldWeight(body:fonz in 15828), product of:
  1.4142135 = tf(termFreq(body:fonz)=2)
  9.679702 = idf(docFreq=16, numDocs=99998)
  0.15625 = fieldNorm(field=body, doc=15828)
-------------------- Result-#:      1, DocId:  18848 --------------------
...

However, the people who are going to use my version of the tool are likely to be more comfortable writing queries (or pasting them from the logs) in the Lucene query syntax. So I have made the query parsing less user-friendly and more programmer-friendly. The result is the ability to specify exactly what you want, for example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
lucli> search title:fonz
3 total matching documents

-------------------- Result-#:      0, DocId:  15827 --------------------
score                  :  5.563311
released         (I-S-): 1980
title            (ITS-): Fonz and the Happy Days Gang, The
-------------------- Result-#:      1, DocId:  18845 --------------------
score                  :  4.867897
released         (I-S-): 1974
title            (ITS-): Happy Days  - A.K.A. the Fonz  #4.10
-------------------- Result-#:      2, DocId:  14808 --------------------
score                  :  4.172483
released         (I-S-): 1999
title            (ITS-): Family Guy  - The Father, the Son and the Holy Fonz  #4.18
lucli> search +title:fonz +released:1999
1 total matching documents

-------------------- Result-#:      0, DocId:  14808 --------------------
score                  :  5.574712
released         (I-S-): 1999
title            (ITS-): Family Guy  - The Father, the Son and the Holy Fonz  #4.18
lucli> 

ITSV Metadata

Knowing the ITSV (Indexed, Tokenized, Stored, Term Vector) metadata for a field can be very useful. For example, a field is searchable and sortable only if it indexed, and sometimes you may forget to set it to indexed when building the index and your search will not pick up the Document, even though you know the Document is there. Well, anyway, this is probably a newbie mistake, but I find that being able to see the ITSV metadata for a field can help in certain cases. Its already available in Luke, so I figured, why not put it in here. You will see this in the vertical orientation only. For example, as you can see below, the released field is Indexed and Stored and the title is Indexed, Tokenized and Stored.

1
2
3
4
5
6
7
8
lucli> search title:"happy days"
56 total matching documents

-------------------- Result-#:      0, DocId:  18843 --------------------
score                  :  7.991356
released         (I-S-): 1970
title            (ITS-): Happy Days
...

Multisearcher Support

Lucli 2.4 did not provide multisearcher support, but sometimes its helpful to see what Documents are being returned from a multisearcher for a given query. Certain commands, however, (such as list, get or remove) are based on a single index backing the searcher, so these commands do not work in multisearcher mode. To build a multisearcher, simply specify multiple paths in the 'index' command. The example below shows how to do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
lucli> index src/test/resources/movieindex1
Index has 99999 documents 
All Fields: [released, body, title]
Indexed Fields: [released, body, title]
lucli> index src/test/resources/movieindex1 src/test/resources/movieindex2
Index has 147520 documents 
All Fields: [released, body, title]
Indexed Fields: [released, body, title]
Multisearcher mode set
lucli> list title
ERROR: Impossible operation, 'index' to reset to single searcher mode

The first call above is to open the movieindex1 index, which has 99,999 documents. The second call opens a multisearcher on the movieindex1 and movieindex2 indexes, with a combined document count of 147,520 documents. As you can see, trying to run the 'list' command results in an error.

JLine Pagination

Lucli 2.4 had the pagination logic for showing 10 records per "page" built into the LuceneMethods.printHits() method. Since JLine already has support for pagination, I decided to move this logic out to JLine. JLine computes the terminal height and considers each line to be newline terminated, so if your index has long fields spanning multiple lines, you will still have to use your terminal scrollbar. Also, the --More-- prompt does not allow you to back up a screen, unlike the behavior of the Unix less. But hopefully, this will show up with a future release of JLine. Here is what it looks like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
lucli> search +title:"happy days" +body:"fonz"
13 total matching documents
-------------------- Result-#:      0, DocId:  18851 --------------------
score                  :  6.010070
released         (I-S-): 1974
title            (ITS-): Happy Days  - Because It's There  #11.1
-------------------- Result-#:      1, DocId:  18855 --------------------
score                  :  6.010070
released         (I-S-): 1974
title            (ITS-): Happy Days  - Cruisin'  #2.16
-------------------- Result-#:      2, DocId:  18858 --------------------
score                  :  5.372923
released         (I-S-): 1974
title            (ITS-): Happy Days  - Fonzie Moves In  #3.1
-------------------- Result-#:      3, DocId:  18863 --------------------
score                  :  5.372923
released         (I-S-): 1974
title            (ITS-): Happy Days  - Hardware Jungle  #1.5
-------------------- Result-#:      4, DocId:  18883 --------------------
score                  :  5.372923
released         (I-S-): 1974
title            (ITS-): Happy Days  - Tall Story  #8.17
-------------------- Result-#:      5, DocId:  18868 --------------------
score                  :  5.190344
released         (I-S-): 1974
--More--

Also, the only results that are part of this pagination is the output of the LuceneMethods.printHits() call. Unlike the original code, a Collection<String> is created by printHits() and passed to Lucli.print() which wraps the call to the JLine paginated output method. So if there is other output, such as the count information above, this is not paginated. The current design also introduces a noticeable lag, at least for the 'list' command, as it builds a Collection of all the formatted output. So, in all, while relying on JLine pagination reduces the application code, I may need to revisit the decision and build the pagination code back into the printHits method so it does a page per call.

Adding/Deleting Commands

To add a command:

  1. Add an enum entry for your command into LucliCommand.java. The arguments for the enum are the Lucli command name, the help message and the minimum number of parameters the command needs to work. For example, 'similarity' can work with 0 parameters, while 'index' needs at least 1 parameter.
  2. Add the case logic for the new enum element in the switch block of the Lucli.handleCommand() method. The preferred approach is to delegate to a method in LucliMethods.java.
  3. Add the method that does what you want in LucliMethods.java

Deleting a command is the reverse of adding a command:

  1. Remove or comment out the enum entry for the command in LucliCommand.java
  2. Comment out the case logic inside the handleCommand() method's switch block in Lucli.java

You will need to recompile for the changes to take effect.

The code for my version of Lucli is shown below. I've used the pygmentize script from the Pygments project to colorize the code, hopefully its easier to read than the code I have been sharing in my previous blogs.

Code: Lucli.java

This is the main class that is called from the shell. If you have the original Lucene distribution, then the jar file is created inside lib, and you can use the run.sh script to run it.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Source: src/main/java/org/apache/lucene/contrib/lucli/Lucli.java
package org.apache.lucene.contrib.lucli;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *    "Apache Lucene" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    "Apache Lucene", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import java.util.Collection;
import jline.ArgumentCompletor;
import jline.Completor;
import jline.ConsoleReader;
import jline.FileNameCompletor;
import jline.History;
import jline.SimpleCompletor;

import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;

/**
 * Main class for lucli: the Lucene Command Line Interface.
 * This class handles mostly the actual CLI part, command names, help, etc.
 */
public class Lucli {

  public final static String DEFAULT_FIELDNAME = "body";
 public final static String HISTORYFILE = ".lucli";
 public final static int MAX_TERMS = 100;
  public final static int MAX_TOKENS = 10;

 private String historyFile;
 private File script = null;
  private ConsoleReader consoleReader = null;

 /**
   * Main entry point. The first argument can be a filename with an
   * application initialization file.
  */
 public Lucli(String[] args) throws IOException {
  String line;
  historyFile = System.getProperty("user.home") +
      File.separator + HISTORYFILE;
  // parse command line arguments (in case we want to use Lucli in script mode)
  parseArgs(args);
  if (script != null) {
    consoleReader = new ConsoleReader(new FileInputStream(script),
        new PrintWriter(System.out));
  } else {
    consoleReader = new ConsoleReader();
      consoleReader.setHistory(new History(new File(historyFile)));
      consoleReader.setUsePagination(true);
  }
  // set completer with list of words
    Completor[] comp = new Completor[] {
      new SimpleCompletor(LucliCommand.getNames()),
      new FileNameCompletor()
    };
    consoleReader.addCompletor (new ArgumentCompletor(comp));
  // main input loop
  LuceneMethods luceneMethods = new LuceneMethods();
  while (true) {
   try {
    line = consoleReader.readLine("lucli> ");
    if (line != null) {
          handleCommand(line, consoleReader, luceneMethods);
    }
   } catch (java.io.EOFException e) {
    System.out.println(""); //new line
    exit();
   } catch (UnsupportedEncodingException e) {
    e.printStackTrace(System.err);
   } catch (IOException e) {
    e.printStackTrace(System.err);
   }
  }
 }

  protected static void message(String s) {
    System.out.println(s);
  }

  protected static void error(String s) {
    message("ERROR: " + s);
  }

 private void handleCommand(String line, ConsoleReader cr,
      LuceneMethods luceneMethods) {
    String[] words = tokenizeCommand(line);
    if (words.length == 0) {
      return; // white space
    }
    if (line.trim().startsWith("#")) {
      return; // # == comment
    }
    LucliCommand command = LucliCommand.fromName(words[0]);
    if (command.minParams > words.length - 1) {
      error(command.help);
      return;
    }
    try {
      switch (command) {
        case INFO:
          luceneMethods.info();
          break;
        case SEARCH:
          print(luceneMethods.search(joinTail(words), false, false));
          break;
        case OPTIMIZE:
          luceneMethods.optimize();
          break;
        case QUIT:
          luceneMethods.closeIndex();
          exit();
        case HELP:
          help();
          break;
        case COUNT:
          luceneMethods.count(joinTail(words));
          break;
        case TERMS:
          luceneMethods.terms(joinTail(words));
          break;
        case INDEX:
          luceneMethods.resetIndex(joinTail(words));
          break;
        case TOKENS:
          print(luceneMethods.search(joinTail(words), false, true));
          break;
        case EXPLAIN:
          print(luceneMethods.search(joinTail(words), true, false));
          break;
        case LIST:
          print(luceneMethods.list(joinTail(words)));
          break;
        case ANALYZER:
          luceneMethods.analyzer(joinTail(words));
          break;
        case SIMILARITY:
          luceneMethods.similarity(joinTail(words));
          break;
        case GET:
          print(luceneMethods.getRecord(joinTail(words)));
          break;
        case ORIENTATION:
          luceneMethods.orientResults(joinTail(words));
          break;
        case REMOVE:
          luceneMethods.removeRecord(joinTail(words));
          break;
        case NOCOMMAND:
          // do nothing
          break;
        case UNKNOWN:
        default:
          error("Unknown command: " + words[0] +
            ", type help for list of commands");
          break;
      }
    } catch (ParseException e) {
      error("Malformed query: " + e.getMessage());
      dumpStack(e);
    } catch (ClassNotFoundException e) {
      error("Class not found: " + e.getMessage());
      dumpStack(e);
    } catch (InstantiationException e) {
      error("Cannot instantiate class: " + e.getMessage() +
        ", ensure default constructor");
      dumpStack(e);
    } catch (IllegalAccessException e) {
      error("Unable to access class: " + e.getMessage());
      dumpStack(e);
    } catch (CorruptIndexException e) {
      error("Index is corrupt");
      dumpStack(e);
    } catch (IOException e) {
      error(e.getMessage());
      dumpStack(e);
    } catch (IllegalArgumentException e) {
      error(e.getMessage());
      dumpStack(e);
    }
  }

  /**
   * Removes the first word from the tokenized word array and returns
   * the rest of it joined into a single string.
   * @param words the array of tokens.
   * @return the string consisting of words[1..words.length-1].
   */
  private String joinTail(String[] words) {
    if (words.length > 1) {
      StringBuilder buf = new StringBuilder();
      for (int i = 1; i < words.length; i++) {
        buf.append(words[i]).append(" ");
      }
      return buf.toString().trim();
    } else {
      return "";
    }
  }

  /**
   * Tokenize the input command line by splitting by space.
   * @param line the input line to be tokenized.
   * @return an array of tokens.
   */
 private String[] tokenizeCommand(String line) {
    return line.split("[ \t]");
 }

 private void exit() {
  System.exit(0);
 }

  /**
   * Prints the help message. This is the "usage" in interactive mode.
   */
 private void help() {
    for (LucliCommand command : LucliCommand.getMap().values()) {
      System.out.println("\t" + command.name + ": " + command.help);
    }
 }

 /*
  * Only parse command line argument --file (or -f).
  */
 private void parseArgs(String[] args) {
   String errorMessage = null;
  if (args.length > 0) {
    if (args.length == 2 && 
        ("--file".equals(args[0]) || "-f".equals(args[0]))) {
      File scriptfile = new File(args[1]);
      if (scriptfile.exists() && scriptfile.canExecute()) {
        this.script = scriptfile;
        return;
      } else {
        errorMessage = "File:" + args[1] +
            " does not exist or is not executable";
      }
    }
   usage(errorMessage);
   System.exit(1);
  }
 }

  /**
   * Prints command line usage information. Includes an error message if
   * appropriate. This is useful in script mode. The error message serves
   * as an indication of where the problem is in the script.
   * @param errorMessage the error thrown by the Lucli command.
   */
 private void usage(String errorMessage) {
  message("Usage: lucli.Lucli [--file script_file]");
  if (errorMessage != null) {
    error(errorMessage);
  }
 }

  /**
   * Dumps the stacktrace in interactive mode. Useful during testing.
   * @param e the Exception to print.
   */
  private void dumpStack(Exception e) {
//    e.printStackTrace();
  }

  /**
   * Paginated printing method for a collection.
   * @param ss the collection of strings to print with pagination.
   */
  private void print(Collection<String> ss) {
    try {
      consoleReader.printColumns(ss);
    } catch (IOException e) {
      error("IO Exception: " + e.getMessage());
    }
  }

  /**
   * This is how we are called.
   * @param args command line arguments. Usage is:
   *        Lucli [--file script_file]
   * @throws IOException if one is thrown.
   */
  public static void main(String[] args) {
    try {
    new Lucli(args);
    } catch (IOException e) {
      // this is thrown by the jline framework and should probably never
      // happen, but we catch it here and report it just in case it does.
      error(e.getMessage());
      e.printStackTrace(System.err);
      System.exit(0);
    }
 }
}

Code: LucliCommand.java

This is a newly introduced Enum that contains all the commands that are available from the Lucli interface, along with their descriptions and the minimum number of parameters that they need to operate. This was originally achieved in Lucli using an inner Command class that did about the same thing, but with Enums we don't need a command id anymore. Also, having an Enum reduces the number of places one needs to change when adding or removing commands from Lucli.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
// Source: src/main/java/org/apache/lucene/contrib/lucli/LucliCommand.java
package org.apache.lucene.contrib.lucli;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *    "Apache Lucene" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    "Apache Lucene", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Enumeration of commands available in Lucli.
 */
public enum LucliCommand {

  NOCOMMAND ("nocommand", null, 0),
 UNKNOWN ("unknown", null, 0),
 INFO ("info", "Display info about current Lucene index.", 0),
 SEARCH ("search", "Search current index. Ex: search query", 1),
 OPTIMIZE ("optimize", "Optimize current index", 0),
 QUIT ("quit", "Quit/Exit Lucli", 0),
 HELP ("help", "Display command help", 0),
 COUNT ("count", "Return number of results from search. Ex: count query", 1),
 TERMS ("terms", "Show first " + Lucli.MAX_TERMS + 
    " terms in this index. Can filter by field name if supplied. " +
    "Ex: terms [field]", 0),
 INDEX ("index", "Choose new lucene index. Ex: index my_index...", 1),
 TOKENS ("tokens", "Returns top " + Lucli.MAX_TOKENS +
    " tokens for each document (Verbose)", 1),
 EXPLAIN ("explain",
    "Generates explanation for the query. Ex: explain query", 1),
 LIST ("list", "List all or named fields in index. Ex: list f1 f2...", 0),
  ANALYZER ("analyzer",
    "Set/Unset custom analyzer, default StandardAnalyzer. " +
    "Ex: analyzer [analyzer_class]", 0),
  GET ("get", "Return the record at the specified position. Ex: rec 0", 1),
  ORIENTATION ("orient",
    "Set result display orientation, default horizontal. " +
    "Ex: orient [vertical|horizontal]", 0),
  SIMILARITY ("similarity",
    "Set/Unset custom similarity, default DefaultSimilarity", 0),
  REMOVE("remove", "Remove record at specified position. Ex: remove 0", 1);

  public String name;
  public String help;
  public int minParams;

  LucliCommand(String name, String help, int minParams) {
    this.name = name;
    this.help = help;
    this.minParams = minParams;
  }

  private static boolean initialized = false;
  private static SortedMap<String,LucliCommand> commandMap =
    new TreeMap<String,LucliCommand>();

  public static LucliCommand fromName(String name) {
    initialize();
    if (commandMap.containsKey(name)) {
      return commandMap.get(name);
    } else {
      return LucliCommand.UNKNOWN;
    }
  }

  public static Map<String,LucliCommand> getMap() {
    initialize();
    return commandMap;
  }

  public static String[] getNames() {
    initialize();
    return commandMap.keySet().toArray(new String[0]);
  }

  private static void initialize() {
    if (! initialized) {
      for (LucliCommand command : LucliCommand.values()) {
        if (command.help != null) {
          commandMap.put(command.name, command);
        }
      }
      initialized = true;
    }
  }
}

Code: LuceneMethods.java

This is almost all Lucene. Apart from the new commands which I have described above, I have tried to use the new features of Lucene 2.4 to address the existing methods.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
// Source: src/main/java/org/apache/lucene/contrib/lucli/LuceneMethods.java
package org.apache.lucene.contrib.lucli;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *    "Apache Lucene" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    "Apache Lucene", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermEnum;
import org.apache.lucene.index.IndexReader.FieldOption;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.DefaultSimilarity;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MultiSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searchable;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.Similarity;
import org.apache.lucene.search.TopDocs;

/**
 * Various methods that interact with Lucene and provide info about the 
 * index, search, etc. Parts addapted from Lucene demo.
 */
class LuceneMethods {

  private String indexName;
  private Searcher searcher;
  private Analyzer analyzer;
  private Similarity similarity;
  private boolean orientVertical = true; // suitable for interactive use
  private boolean isMultisearcher = false;

  public LuceneMethods() {
    super();
    this.analyzer = new StandardAnalyzer();
    this.similarity = new DefaultSimilarity();
    Lucli.message("Lucene CLI. Please specify index. Type 'help' for instructions.");
  }

  /**
   * Called from "index" command. Attempts to open the new index. If it can,
   * it resets the current index to the one pointed at by indexName.
   * @param indexName the index name to set.
   * @throws CorruptIndexException
   * @throws IOException
   */
  public void resetIndex(String indexName) 
      throws CorruptIndexException, IOException {
    Searcher newSearcher = openIndex(indexName, false);
    closeIndex(); // close the current index
    this.searcher = newSearcher;
    if (isMultisearcher) {
      this.indexName = indexName.split(" ")[0];
    } else {
      this.indexName = indexName;
    }
  }

  /**
   * Closes the index before quitting. Also called from the resetIndex method
   * to close the handle for the previous searcher, if it exists.
   */
  public void closeIndex() {
    if (searcher != null) {
      try {
        searcher.close();
      } catch (IOException e) {
        // swallow it, not much we can do here
      }
    }
  }

  /**
   * Called from "info" command. Delegates to the private version of this
   * method which checks to see if the index is valid and prints some
   * information about the index.
   * @throws IOException if index does not exist or is corrupt.
   */
  public void info() throws IOException {
    info(this.indexName, this.searcher);
  }

  /**
   * Allows setting/resetting the similarity implementation used by the
   * searcher. Default is DefaultSimilarity. If called without an argument,
   * returns the currently configured Similarity. This method is called from
   * the "similarity" command.
   * @param similarity the full class name of the Similarity implementation.
   * @throws ClassNotFoundException
   * @throws InstantiationException
   * @throws IllegalAccessException
   */
  public void similarity(String similarity) 
      throws ClassNotFoundException, InstantiationException,
      IllegalAccessException {
    if (similarity.trim().length() == 0) {
      this.similarity = new DefaultSimilarity();
    } else {
      Similarity newSimilarity =
        (Similarity) Class.forName(similarity).newInstance();
      this.similarity = newSimilarity;
    }
    Lucli.message("Similarity set: " + this.similarity.getClass().getName());
  }
  
  /**
   * Allows setting/resetting the Analyzer. Default is StandardAnalyzer. If
   * called without arguments, returns the class name of the Analyzer in use.
   * Called from the "analyzer" command.
   * @param analyzer the class name of the analyzer to set, or empty string.
   */
  public void analyzer(String analyzer) 
      throws ClassNotFoundException, InstantiationException,
      IllegalAccessException {
    if (analyzer.trim().length() == 0) {
      // reset analyzer back to default
      this.analyzer = new StandardAnalyzer();
    } else {
      Analyzer newAnalyzer = (Analyzer) Class.forName(analyzer).newInstance();
      this.analyzer = newAnalyzer;
    }
    Lucli.message("Analyzer set: " + this.analyzer.getClass().getName());
  }

  /**
   * Allows setting result orientation. Default is vertical, which is more
   * convenient for interactive use. Horizontal orientation is more convenient
   * for batch use for scripting, etc. Called from the "orient" command. If
   * supplied without arguments, returns the current orientation setting.
   * @param orientation the orientation to set (vertical or horizontal).
   */
  public void orientResults(String orientation) {
    if (orientation == null || orientation.trim().length() == 0) {
      // return the current orientation
      Lucli.message("Result orientation is " +
        (this.orientVertical ? "vertical" : "horizontal"));
    } else {
      if (orientation.startsWith("vert")) {
        this.orientVertical = true;
      } else if (orientation.startsWith("hori")) {
        this.orientVertical = false;
      } else {
        Lucli.message("Invalid orientation, valid values vertical or horizontal");
      }
    }
  }

  /**
   * Called from "count" command. Returns the number of documents satisfying
   * the query. The query must be a well formed query in Lucene's query syntax.
   * @param queryString the query string.
   * @throws IOException
   * @throws ParseException
   */
  public void count(String queryString) throws IOException, ParseException {
    Query query = parse(queryString);
    int count = initSearch(query).length;
    Lucli.message(count + " total documents");
  }

  /**
   * Called from the "search", "list", "count", and "explain" commands.
   * Sends a query to the underlying index and returns the results. Can also
   * print the explain plan for the query, as well as the tokens returned.
   * @param queryString the Lucene query string.
   * @param explain if true, shows the explanation for each document returned.
   * @param showTokens if true, shows the tokens found for each document.
   * @throws IOException
   * @throws ParseException
   */
  public List<String> search(String queryString, boolean explain,
      boolean showTokens) throws IOException, ParseException {
    List<String> results = new ArrayList<String>();
    Query query = parse(queryString);
    ScoreDoc[] scoreDocs = initSearch(query);
    if (explain) {
      Lucli.message("Rewritten query: " + query.toString());
    }
    Lucli.message(scoreDocs.length + " total matching documents");
    int nresult = 0;
    for (ScoreDoc scoreDoc : scoreDocs) {
      int docId = scoreDoc.doc;
      float score = scoreDoc.score;
      Document doc = searcher.doc(docId);
      results.addAll(printHit(doc, docId, score, nresult, null,
        query, showTokens, explain));
      nresult++;
    }
    return results;
  }

  /**
   * Lists all records in the index. If a field list is supplied, then only
   * prints the fields named in the list. If no list is supplied, all the
   * fields are output.
   * @param fieldList a space separated list of field names.
   * @throws CorruptIndexException
   * @throws IOException
   */
  public List<String> list(String fieldList)
      throws CorruptIndexException, IOException {
    validateIndexSet();
    validateOperationPossible();
    List<String> results = new ArrayList<String>();
    IndexReader reader = null;
    try {
      reader = IndexReader.open(indexName);
      Set<String> fields = new HashSet<String>();
      if (fieldList.trim().length() == 0) {
        fields.addAll(reader.getFieldNames(FieldOption.ALL));
      } else {
        fields.addAll(Arrays.asList(fieldList.split(" ")));
      }
      int numDocs = reader.maxDoc();
      for (int i = 0; i < numDocs; i++) {
        if (reader.isDeleted(i)) {
          continue;
        }
        Document doc = reader.document(i);
        results.addAll(printHit(doc, i, -1.0F, i, fields, null, false, false));
      }
    } finally {
      closeReader(reader);
    }
    return results;
  }

  /**
   * Gets the document specified by docId from the current index.
   * @param docId the docId of the document to get.
   * @throws NumberFormatException
   * @throws CorruptIndexException
   * @throws IOException
   */
  public List<String> getRecord(String docId) throws
      CorruptIndexException, IOException {
    validateIndexSet();
    validateOperationPossible();
    IndexReader reader = IndexReader.open(indexName);
    int numDocs = reader.maxDoc();
    int docid = validateDocId(docId, numDocs);
    List<String> results = new ArrayList<String>();
    try {
      Document doc = reader.document(docid);
      results.addAll(printHit(doc, docid, -1.0F, 0, null, null, false, false));
    } finally {
      closeReader(reader);
    }
    return results;
  }

  /**
   * Open the current index with a IndexWriter and optimize it.
   * @throws IOException
   */
  public void optimize() throws IOException {
    validateIndexSet();
    validateOperationPossible();
    IndexWriter writer = null;
    try {
      writer = new IndexWriter(indexName, analyzer, false,
        MaxFieldLength.UNLIMITED);
      Lucli.message("Starting to optimize index.");
      long start = System.currentTimeMillis();
      writer.optimize();
      writer.commit();
      Lucli.message("Done optimizing index. Took " +
        (System.currentTimeMillis() - start) + " msecs");
    } catch (IOException e) {
      Lucli.error("IO Error, Optimization may have failed");
    } finally {
      closeWriter(writer);
    }
  }

  public void removeRecord(String docId) throws CorruptIndexException,
      IOException {
    validateIndexSet();
    validateOperationPossible();
    IndexReader reader = null;
    try {
      reader = IndexReader.open(indexName);
      int numDocs = reader.maxDoc();
      int docid = validateDocId(docId, numDocs);
      reader.deleteDocument(docid);
      Lucli.message("Document " + docId + " deleted");
    } finally {
      closeReader(reader);
    }
  }

  /**
   * Provides a list of the top terms of the index.
   * @param field  - the name of the command or empty for all.
   * @throws CorruptIndexException
   * @throws IOException
   */
  public void terms(String field) throws CorruptIndexException, IOException {
    validateIndexSet();
    validateOperationPossible();
    SortedMap<String,Integer> termMap = new TreeMap<String,Integer>();
    IndexReader reader = null;
    try {
      reader = IndexReader.open(indexName);
      TermEnum terms = reader.terms();
      while (terms.next()) {
        Term term = terms.term();
        if ((field.trim().length() == 0) || field.equals(term.field())) {
          termMap.put(term.field() + ":" + term.text(),
            new Integer((terms.docFreq())));
        }
      }
      int nkeys = 0;
      for (String key : termMap.keySet()) {
        Lucli.message(key + ": " + termMap.get(key));
        nkeys++;
        if (nkeys > Lucli.MAX_TERMS) {
          break;
        }
      }
    } finally {
      closeReader(reader);
    }
  }

  /**
   * Opens a new index and sets the searcher variable. If multiple index names
   * are supplied to the index command, a Multisearcher is created. In multi-
   * searcher mode, a number of commands that depend on a single searcher
   * such as get, remove, etc, will refuse to work until a single index is
   * set (so it switches to using a single searcher).
   * @param indexName the name of the index.
   * @param setSearcher if true, sets the searcher with the new searcher.
   * @return a Searcher object representing the new index.
   * @throws CorruptIndexException
   * @throws IOException
   */
  private Searcher openIndex(String indexName, boolean setSearcher)
      throws CorruptIndexException, IOException {
    Searcher newSearcher = null;
    if (indexName.contains(" ")) {
      isMultisearcher = true;
      String[] indexNames = indexName.split(" ");
      Searchable[] searchables = new Searchable[indexNames.length];
      for (int i = 0; i < searchables.length; i++) {
        searchables[i] = new IndexSearcher(indexNames[i]);
      }
      newSearcher = new MultiSearcher(searchables);
      if (setSearcher) {
        this.searcher = newSearcher;
        this.indexName = indexNames[0];
      }
      info(indexNames[0], newSearcher);
    } else {
      isMultisearcher = false;
      newSearcher = new IndexSearcher(indexName);
      if (setSearcher) {
        this.searcher = newSearcher;
        this.indexName = indexName;
      }
      info(indexName, newSearcher);
    }
    return newSearcher;
  }

  /**
   * Common functionality to report on the current state of an index.
   * @param indexName the index name.
   * @param searcher the Searcher reference.
   * @throws IOException
   */
  private void info(String indexName, Searcher searcher) throws IOException {
    Lucli.message("Index has " + searcher.maxDoc() + " documents ");
    Lucli.message("All Fields: " + getFieldsInfo(indexName, FieldOption.ALL));
    Lucli.message("Indexed Fields: " +
      getFieldsInfo(indexName, FieldOption.INDEXED));
    if (isMultisearcher) {
      Lucli.message("Multisearcher mode set");
    }
  }

  /**
   * Returns the field names in the index.
   * @param indexName the index name.
   * @param fieldOption a filter to show a subset of the field names.
   * @return a Stringified list of all field names.
   * @throws CorruptIndexException
   * @throws IOException
   */
  private String getFieldsInfo(String indexName, FieldOption fieldOption)
          throws CorruptIndexException, IOException {
    IndexReader reader = IndexReader.open(indexName);
    Collection<String> fieldnames = reader.getFieldNames(fieldOption);
    return fieldnames.toString();
  }

  /**
   * Convenience method to print out a Document into a List of formatted
   * strings. Behavior differs based on current orientation setting. The
   * List is passed into the ConsoleReader's printCollection method to
   * ensure pagination.
   * @param doc the Document to print into a List.
   * @param docId the document id of the document.
   * @param score the score for the document.
   * @param resultId the result id for the current search results.
   * @param fieldList the field list to show. This is only used in case of
   * the 'list' command, other commands such as 'search' and 'get' print all
   * fields in the Document.
   * @param query the Query passed in, is null if called from 'list' or 'get'
   * commands.
   * @param showTokens true or false.
   * @param explainQuery true or false.
   * @return a List of Strings representing a single Document.
   * @throws IOException
   */
  private List<String> printHit(Document doc, int docId, float score,
      int resultId, Set<String> fieldList, Query query, boolean showTokens,
      boolean explainQuery) throws IOException {
    List<String> results = new ArrayList<String>();
    List<Field> fields = doc.getFields();
    if (orientVertical) {
      results.add(String.format(
        "-------------------- Result-#: %6d, DocId: %6d --------------------%n",
        resultId, docId));
      if (score > 0.0F) {
        results.add(String.format("%-23s: %9.6f%n", "score", score));
      }
      for (Field field : fields) {
        String fieldName = field.name();
        if (fieldList != null && (! fieldList.contains(fieldName))) {
          continue;
        }
        String fieldValue = doc.get(fieldName);
        results.add(String.format("%-16s (%s%s%s%s): %s%n", fieldName,
          (field.isIndexed() ? "I" : "-"),
          (field.isTokenized() ? "T" : "-"),
          (field.isStored() ? "S" : "-"),
          (field.isTermVectorStored() ? "V" : "-"), fieldValue));
      }
      if (showTokens) {
        results.add(String.format("%-23s: %s%n", "Tokens", invertDocument(doc)));
      }
      if (explainQuery && query != null) {
        results.add(String.format("%-23s: %s%n", "Explanation",
          explainQuery(query, docId)));
      }
    } else {
      StringBuilder buf;
      if (resultId == 0) {
        // if this is the first record, also print the heading
        buf = new StringBuilder();
        buf.append("##resultId;docId");
        if (score > 0.0F) {
          buf.append(";score");
        }
        for (Field field : fields) {
          buf.append(";").append(field.name());
        }
        if (showTokens) {
          buf.append(";Tokens");
        }
        if (explainQuery && query != null) {
          buf.append(";Explanation");
        }
        results.add(buf.toString());
      }
      buf = new StringBuilder();
      buf.append(resultId).append(";").append(docId);
      if (score > 0.0F) {
        buf.append(String.format("%9.6f", score));
      }
      for (Field field : fields) {
        buf.append(";").append(doc.get(field.name()));
      }
      if (showTokens) {
        buf.append(";").append(invertDocument(doc));
      }
      if (explainQuery && query != null) {
        buf.append(";").
            append(explainQuery(query, docId).replaceAll("\n", "<br/>"));
      }
      results.add(buf.toString());
    }
    return results;
  }

  /**
   * Calculates and returns the Explanation for the specified Query
   * and docId.
   * @param query the query to analyze.
   * @param docId the docId to generate the explanation for.
   * @throws IOException
   */
  private String explainQuery(Query query, int docId) throws IOException {
    validateIndexSet();
    return searcher.explain(query, docId).toString();
  }

  /**
   * Parse the query string into a Query object using Lucene's QueryParser.
   * @param queryString the Lucene query string to parse.
   * @return
   * @throws java.io.IOException
   * @throws org.apache.lucene.queryParser.ParseException
   */
  private Query parse(String queryString) throws IOException, ParseException {
    QueryParser parser = new QueryParser(Lucli.DEFAULT_FIELDNAME, analyzer);
    Query query = null;
    query = parser.parse(queryString);
    return query;
  }

  /**
   * Searches using the passed in query. Unlike the original Lucli, the
   * assumption here is that the user knows Lucene's query syntax, so they
   * can send in the fully formed query.
   * @param queryString the query in Lucene's query syntax.
   * @return an array of ScoreDoc objects.
   * @throws IOException if one is thrown by underlying Lucene index.
   * @throws ParseException if there was a problem with the query.
   */
  private ScoreDoc[] initSearch(Query query) throws IOException {
    validateIndexSet();
    int maxDocs = searcher.maxDoc();
    TopDocs topDocs = searcher.search(query, null, maxDocs);
    return topDocs.scoreDocs;
  }

  /**
   * Find all the tokens for the various fields (indexed and tokenized) fields
   * in this document and return it in decreasing frequency order.
   * @param doc the Document to analyze.
   * @return the result string.
   * @throws IOException
   */
  private String invertDocument(Document doc) throws IOException {
    Map<String,Integer> counts = new HashMap<String,Integer>();
    for (Object obj : doc.getFields()) {
      Field field = (Field) obj;
      if (field.isIndexed() && field.isTokenized()) {
        Reader reader = null;
        if (field.readerValue() != null) {
          reader = field.readerValue();
        } else if (field.stringValue() != null) {
          reader = new StringReader(field.stringValue());
        } else {
          continue;
        }
        TokenStream stream = analyzer.tokenStream(field.name(), reader);
        try {
          Token t = new Token();
          while ((t = stream.next(t)) != null) {
            String term = t.term();
            if (counts.containsKey(term)) {
              int orig = counts.get(term);
              counts.put(term, orig + 1);
            } else {
              counts.put(term, 1);
            }
          }
        } finally {
          stream.close();
        }
      }
    }
    List<Entry<String, Integer>> entryList =
      new ArrayList<Entry<String, Integer>>();
    entryList.addAll(counts.entrySet());
    Collections.sort(entryList, new Comparator<Entry<String, Integer>>() {
      public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
        return o2.getValue().compareTo(o1.getValue());
      }
    });
    StringBuilder tokbuf = new StringBuilder();
    int ntoks = 0;
    for (Entry<String, Integer> entry : entryList) {
      if (ntoks > 0) {
        tokbuf.append(",");
      }
      tokbuf.append(entry.getKey()).append("(").
              append(entry.getValue()).append(")");
      ntoks++;
    }
    return tokbuf.toString();
  }

  /**
   * Convenience method to close an IndexReader quietly.
   * @param reader the IndexReader to close.
   */
  private void closeReader(IndexReader reader) {
    if (reader != null) {
      try {
        reader.close();
      } catch (Exception e) {
        // swallow it, not much we can do at this stage
      }
    }
  }

  /**
   * Convenience method to close an IndexWriter quietly.
   * @param writer the IndexWriter to close.
   */
  private void closeWriter(IndexWriter writer) {
    if (writer != null) {
      try {
        writer.close();
      } catch (Exception e) {
        // swallow it, not much we can do at this stage
      }
    }
  }

  /**
   * Checks to see if the indexName and searcher global variables are
   * set, else throws an IllegalArgumentException.
   * @throws IllegalArgumentException
   */
  private void validateIndexSet() {
    if (indexName == null || searcher == null) {
      throw new IllegalArgumentException(LucliCommand.INDEX.help);
    }
  }

  /**
   * Checks that the docId supplied is numeric and within range, else throws
   * an IllegalArgumentException.
   * @param docId the docId to look up or remove.
   * @param numDocs the number of documents in the Index.
   * @return the docId as an Int.
   */
  private int validateDocId(String docId, int numDocs) {
    int docid = -1;
    try {
      docid = Integer.parseInt(docId);
    } catch (NumberFormatException e) {
      throw new IllegalArgumentException("docId must be numeric");
    }
    if ((docid < 0) || (docid > numDocs - 1)) {
      throw new IllegalArgumentException(
        "DocId must be in range:[0.." + (numDocs - 1) + "]");
    }
    return docid;
  }

  private void validateOperationPossible() {
    if (isMultisearcher) {
      throw new IllegalArgumentException(
        "Impossible operation, 'index' to reset to single searcher mode");
    }
  }
}

2 comments (moderated to prevent spam):

guigouz said...

would you share this source code in a downloadable format ?

thanks

Sujit Pal said...

Sure, send me your email address in a comment (I won't publish it), and I can send the files over as an attachment. Although you can save yourself the trouble and cut-paste from the post here - the files are going to be indentical.