old python needs __main__ to call a module
[pylucene.git] / samples / mansearch.py
1 # ====================================================================
2 #   Licensed under the Apache License, Version 2.0 (the "License");
3 #   you may not use this file except in compliance with the License.
4 #   You may obtain a copy of the License at
5 #
6 #       http://www.apache.org/licenses/LICENSE-2.0
7 #
8 #   Unless required by applicable law or agreed to in writing, software
9 #   distributed under the License is distributed on an "AS IS" BASIS,
10 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 #   See the License for the specific language governing permissions and
12 #   limitations under the License.
13 # ====================================================================
14 #
15 # Author: Erik Hatcher
16 #
17 # to query the index generated with manindex.py
18 #  python mansearch.py <query>
19 # by default, the index is stored in 'pages', which can be overriden with
20 # the MANDEX environment variable
21 # ====================================================================
22
23
24 import sys, os
25
26 from string import Template
27 from datetime import datetime
28 from getopt import getopt, GetoptError
29
30 from lucene import \
31      Document, IndexSearcher, SimpleFSDirectory, File, QueryParser, \
32      StandardAnalyzer, initVM, Version
33
34 if __name__ == '__main__':
35     initVM()
36
37 def usage():
38     print sys.argv[0], "[--format=<format string>] [--index=<index dir>] [--stats] <query...>"
39     print "default index is found from MANDEX environment variable"
40
41 try:
42     options, args = getopt(sys.argv[1:], '', ['format=', 'index=', 'stats'])
43 except GetoptError:
44     usage()
45     sys.exit(2)
46
47
48 format = "#name"
49 indexDir = os.environ.get('MANDEX') or 'pages'
50 stats = False
51 for o, a in options:
52     if o == "--format":
53         format = a
54     elif o == "--index":
55         indexDir = a
56     elif o == "--stats":
57         stats = True
58
59
60 class CustomTemplate(Template):
61     delimiter = '#'
62
63 template = CustomTemplate(format)
64
65 fsDir = SimpleFSDirectory(File(indexDir))
66 searcher = IndexSearcher(fsDir, True)
67
68 analyzer = StandardAnalyzer(Version.LUCENE_CURRENT)
69 parser = QueryParser(Version.LUCENE_CURRENT, "keywords", analyzer)
70 parser.setDefaultOperator(QueryParser.Operator.AND)
71 query = parser.parse(' '.join(args))
72 start = datetime.now()
73 scoreDocs = searcher.search(query, 50).scoreDocs
74 duration = datetime.now() - start
75 if stats:
76     print >>sys.stderr, "Found %d document(s) (in %s) that matched query '%s':" %(len(scoreDocs), duration, query)
77
78 for scoreDoc in scoreDocs:
79     doc = searcher.doc(scoreDoc.doc)
80     table = dict((field.name(), field.stringValue())
81                  for field in doc.getFields())
82     print template.substitute(table)